* (bug 3480) MediaWiki:Historywarning now has a parameter that contains the number...
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
13 *
14 */
15 class Article {
16 /**@{{
17 * @private
18 */
19 var $mComment = ''; //!<
20 var $mContent; //!<
21 var $mContentLoaded = false; //!<
22 var $mCounter = -1; //!< Not loaded
23 var $mCurID = -1; //!< Not loaded
24 var $mDataLoaded = false; //!<
25 var $mForUpdate = false; //!<
26 var $mGoodAdjustment = 0; //!<
27 var $mIsRedirect = false; //!<
28 var $mLatest = false; //!<
29 var $mMinorEdit; //!<
30 var $mOldId; //!<
31 var $mPreparedEdit = false; //!< Title object if set
32 var $mRedirectedFrom = null; //!< Title object if set
33 var $mRedirectTarget = null; //!< Title object if set
34 var $mRedirectUrl = false; //!<
35 var $mRevIdFetched = 0; //!<
36 var $mRevision; //!<
37 var $mTimestamp = ''; //!<
38 var $mTitle; //!<
39 var $mTotalAdjustment = 0; //!<
40 var $mTouched = '19700101000000'; //!<
41 var $mUser = -1; //!< Not loaded
42 var $mUserText = ''; //!<
43 var $mParserOptions; //!<
44 var $mParserOutput; //!<
45 /**@}}*/
46
47 /**
48 * Constructor and clear the article
49 * @param $title Reference to a Title object.
50 * @param $oldId Integer revision ID, null to fetch from request, zero for current
51 */
52 public function __construct( Title $title, $oldId = null ) {
53 $this->mTitle =& $title;
54 $this->mOldId = $oldId;
55 }
56
57 /**
58 * Constructor from an article article
59 * @param $id The article ID to load
60 */
61 public static function newFromID( $id ) {
62 $t = Title::newFromID( $id );
63 return $t == null ? null : new Article( $t );
64 }
65
66 /**
67 * Tell the page view functions that this view was redirected
68 * from another page on the wiki.
69 * @param $from Title object.
70 */
71 public function setRedirectedFrom( $from ) {
72 $this->mRedirectedFrom = $from;
73 }
74
75 /**
76 * If this page is a redirect, get its target
77 *
78 * The target will be fetched from the redirect table if possible.
79 * If this page doesn't have an entry there, call insertRedirect()
80 * @return mixed Title object, or null if this page is not a redirect
81 */
82 public function getRedirectTarget() {
83 if( !$this->mTitle || !$this->mTitle->isRedirect() )
84 return null;
85 if( !is_null($this->mRedirectTarget) )
86 return $this->mRedirectTarget;
87 # Query the redirect table
88 $dbr = wfGetDB( DB_SLAVE );
89 $row = $dbr->selectRow( 'redirect',
90 array('rd_namespace', 'rd_title'),
91 array('rd_from' => $this->getID() ),
92 __METHOD__
93 );
94 if( $row ) {
95 return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
96 }
97 # This page doesn't have an entry in the redirect table
98 return $this->mRedirectTarget = $this->insertRedirect();
99 }
100
101 /**
102 * Insert an entry for this page into the redirect table.
103 *
104 * Don't call this function directly unless you know what you're doing.
105 * @return Title object
106 */
107 public function insertRedirect() {
108 $retval = Title::newFromRedirect( $this->getContent() );
109 if( !$retval ) {
110 return null;
111 }
112 $dbw = wfGetDB( DB_MASTER );
113 $dbw->replace( 'redirect', array('rd_from'),
114 array(
115 'rd_from' => $this->getID(),
116 'rd_namespace' => $retval->getNamespace(),
117 'rd_title' => $retval->getDBkey()
118 ),
119 __METHOD__
120 );
121 return $retval;
122 }
123
124 /**
125 * Get the Title object this page redirects to
126 *
127 * @return mixed false, Title of in-wiki target, or string with URL
128 */
129 public function followRedirect() {
130 $text = $this->getContent();
131 return $this->followRedirectText( $text );
132 }
133
134 /**
135 * Get the Title object this text redirects to
136 *
137 * @return mixed false, Title of in-wiki target, or string with URL
138 */
139 public function followRedirectText( $text ) {
140 $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
141 # process if title object is valid and not special:userlogout
142 if( $rt ) {
143 if( $rt->getInterwiki() != '' ) {
144 if( $rt->isLocal() ) {
145 // Offsite wikis need an HTTP redirect.
146 //
147 // This can be hard to reverse and may produce loops,
148 // so they may be disabled in the site configuration.
149 $source = $this->mTitle->getFullURL( 'redirect=no' );
150 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
151 }
152 } else {
153 if( $rt->getNamespace() == NS_SPECIAL ) {
154 // Gotta handle redirects to special pages differently:
155 // Fill the HTTP response "Location" header and ignore
156 // the rest of the page we're on.
157 //
158 // This can be hard to reverse, so they may be disabled.
159 if( $rt->isSpecial( 'Userlogout' ) ) {
160 // rolleyes
161 } else {
162 return $rt->getFullURL();
163 }
164 }
165 return $rt;
166 }
167 }
168 // No or invalid redirect
169 return false;
170 }
171
172 /**
173 * get the title object of the article
174 */
175 public function getTitle() {
176 return $this->mTitle;
177 }
178
179 /**
180 * Clear the object
181 * @private
182 */
183 public function clear() {
184 $this->mDataLoaded = false;
185 $this->mContentLoaded = false;
186
187 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
188 $this->mRedirectedFrom = null; # Title object if set
189 $this->mRedirectTarget = null; # Title object if set
190 $this->mUserText =
191 $this->mTimestamp = $this->mComment = '';
192 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
193 $this->mTouched = '19700101000000';
194 $this->mForUpdate = false;
195 $this->mIsRedirect = false;
196 $this->mRevIdFetched = 0;
197 $this->mRedirectUrl = false;
198 $this->mLatest = false;
199 $this->mPreparedEdit = false;
200 }
201
202 /**
203 * Note that getContent/loadContent do not follow redirects anymore.
204 * If you need to fetch redirectable content easily, try
205 * the shortcut in Article::followContent()
206 *
207 * @return Return the text of this revision
208 */
209 public function getContent() {
210 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
211 wfProfileIn( __METHOD__ );
212 if( $this->getID() === 0 ) {
213 # If this is a MediaWiki:x message, then load the messages
214 # and return the message value for x.
215 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
216 # If this is a system message, get the default text.
217 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
218 $wgMessageCache->loadAllMessages( $lang );
219 $text = wfMsgGetKey( $message, false, $lang, false );
220 if( wfEmptyMsg( $message, $text ) )
221 $text = '';
222 } else {
223 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
224 }
225 wfProfileOut( __METHOD__ );
226 return $text;
227 } else {
228 $this->loadContent();
229 wfProfileOut( __METHOD__ );
230 return $this->mContent;
231 }
232 }
233
234 /**
235 * Get the text of the current revision. No side-effects...
236 *
237 * @return Return the text of the current revision
238 */
239 public function getRawText() {
240 // Check process cache for current revision
241 if( $this->mContentLoaded && $this->mOldId == 0 ) {
242 return $this->mContent;
243 }
244 $rev = Revision::newFromTitle( $this->mTitle );
245 $text = $rev ? $rev->getRawText() : false;
246 return $text;
247 }
248
249 /**
250 * This function returns the text of a section, specified by a number ($section).
251 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
252 * the first section before any such heading (section 0).
253 *
254 * If a section contains subsections, these are also returned.
255 *
256 * @param $text String: text to look in
257 * @param $section Integer: section number
258 * @return string text of the requested section
259 * @deprecated
260 */
261 public function getSection( $text, $section ) {
262 global $wgParser;
263 return $wgParser->getSection( $text, $section );
264 }
265
266 /**
267 * Get the text that needs to be saved in order to undo all revisions
268 * between $undo and $undoafter. Revisions must belong to the same page,
269 * must exist and must not be deleted
270 * @param $undo Revision
271 * @param $undoafter Revision Must be an earlier revision than $undo
272 * @return mixed string on success, false on failure
273 */
274 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
275 $undo_text = $undo->getText();
276 $undoafter_text = $undoafter->getText();
277 $cur_text = $this->getContent();
278 if ( $cur_text == $undo_text ) {
279 # No use doing a merge if it's just a straight revert.
280 return $undoafter_text;
281 }
282 $undone_text = '';
283 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
284 return false;
285 return $undone_text;
286 }
287
288 /**
289 * @return int The oldid of the article that is to be shown, 0 for the
290 * current revision
291 */
292 public function getOldID() {
293 if( is_null( $this->mOldId ) ) {
294 $this->mOldId = $this->getOldIDFromRequest();
295 }
296 return $this->mOldId;
297 }
298
299 /**
300 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
301 *
302 * @return int The old id for the request
303 */
304 public function getOldIDFromRequest() {
305 global $wgRequest;
306 $this->mRedirectUrl = false;
307 $oldid = $wgRequest->getVal( 'oldid' );
308 if( isset( $oldid ) ) {
309 $oldid = intval( $oldid );
310 if( $wgRequest->getVal( 'direction' ) == 'next' ) {
311 $nextid = $this->mTitle->getNextRevisionID( $oldid );
312 if( $nextid ) {
313 $oldid = $nextid;
314 } else {
315 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
316 }
317 } elseif( $wgRequest->getVal( 'direction' ) == 'prev' ) {
318 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
319 if( $previd ) {
320 $oldid = $previd;
321 }
322 }
323 }
324 if( !$oldid ) {
325 $oldid = 0;
326 }
327 return $oldid;
328 }
329
330 /**
331 * Load the revision (including text) into this object
332 */
333 function loadContent() {
334 if( $this->mContentLoaded ) return;
335 wfProfileIn( __METHOD__ );
336 # Query variables :P
337 $oldid = $this->getOldID();
338 # Pre-fill content with error message so that if something
339 # fails we'll have something telling us what we intended.
340 $this->mOldId = $oldid;
341 $this->fetchContent( $oldid );
342 wfProfileOut( __METHOD__ );
343 }
344
345
346 /**
347 * Fetch a page record with the given conditions
348 * @param $dbr Database object
349 * @param $conditions Array
350 */
351 protected function pageData( $dbr, $conditions ) {
352 $fields = array(
353 'page_id',
354 'page_namespace',
355 'page_title',
356 'page_restrictions',
357 'page_counter',
358 'page_is_redirect',
359 'page_is_new',
360 'page_random',
361 'page_touched',
362 'page_latest',
363 'page_len',
364 );
365 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
366 $row = $dbr->selectRow(
367 'page',
368 $fields,
369 $conditions,
370 __METHOD__
371 );
372 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
373 return $row ;
374 }
375
376 /**
377 * @param $dbr Database object
378 * @param $title Title object
379 */
380 public function pageDataFromTitle( $dbr, $title ) {
381 return $this->pageData( $dbr, array(
382 'page_namespace' => $title->getNamespace(),
383 'page_title' => $title->getDBkey() ) );
384 }
385
386 /**
387 * @param $dbr Database
388 * @param $id Integer
389 */
390 protected function pageDataFromId( $dbr, $id ) {
391 return $this->pageData( $dbr, array( 'page_id' => $id ) );
392 }
393
394 /**
395 * Set the general counter, title etc data loaded from
396 * some source.
397 *
398 * @param $data Database row object or "fromdb"
399 */
400 public function loadPageData( $data = 'fromdb' ) {
401 if( $data === 'fromdb' ) {
402 $dbr = wfGetDB( DB_MASTER );
403 $data = $this->pageDataFromId( $dbr, $this->getId() );
404 }
405
406 $lc = LinkCache::singleton();
407 if( $data ) {
408 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
409
410 $this->mTitle->mArticleID = intval( $data->page_id );
411
412 # Old-fashioned restrictions
413 $this->mTitle->loadRestrictions( $data->page_restrictions );
414
415 $this->mCounter = intval( $data->page_counter );
416 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
417 $this->mIsRedirect = intval( $data->page_is_redirect );
418 $this->mLatest = intval( $data->page_latest );
419 } else {
420 if( is_object( $this->mTitle ) ) {
421 $lc->addBadLinkObj( $this->mTitle );
422 }
423 $this->mTitle->mArticleID = 0;
424 }
425
426 $this->mDataLoaded = true;
427 }
428
429 /**
430 * Get text of an article from database
431 * Does *NOT* follow redirects.
432 * @param $oldid Int: 0 for whatever the latest revision is
433 * @return string
434 */
435 function fetchContent( $oldid = 0 ) {
436 if( $this->mContentLoaded ) {
437 return $this->mContent;
438 }
439
440 $dbr = wfGetDB( DB_MASTER );
441
442 # Pre-fill content with error message so that if something
443 # fails we'll have something telling us what we intended.
444 $t = $this->mTitle->getPrefixedText();
445 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
446 $this->mContent = wfMsgNoTrans( 'missing-article', $t, $d ) ;
447
448 if( $oldid ) {
449 $revision = Revision::newFromId( $oldid );
450 if( is_null( $revision ) ) {
451 wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
452 return false;
453 }
454 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
455 if( !$data ) {
456 wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
457 return false;
458 }
459 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
460 $this->loadPageData( $data );
461 } else {
462 if( !$this->mDataLoaded ) {
463 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
464 if( !$data ) {
465 wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
466 return false;
467 }
468 $this->loadPageData( $data );
469 }
470 $revision = Revision::newFromId( $this->mLatest );
471 if( is_null( $revision ) ) {
472 wfDebug( __METHOD__." failed to retrieve current page, rev_id {$this->mLatest}\n" );
473 return false;
474 }
475 }
476
477 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
478 // We should instead work with the Revision object when we need it...
479 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
480
481 $this->mUser = $revision->getUser();
482 $this->mUserText = $revision->getUserText();
483 $this->mComment = $revision->getComment();
484 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
485
486 $this->mRevIdFetched = $revision->getId();
487 $this->mContentLoaded = true;
488 $this->mRevision =& $revision;
489
490 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
491
492 return $this->mContent;
493 }
494
495 /**
496 * Read/write accessor to select FOR UPDATE
497 *
498 * @param $x Mixed: FIXME
499 */
500 public function forUpdate( $x = NULL ) {
501 return wfSetVar( $this->mForUpdate, $x );
502 }
503
504 /**
505 * Get the database which should be used for reads
506 *
507 * @return Database
508 * @deprecated - just call wfGetDB( DB_MASTER ) instead
509 */
510 function getDB() {
511 wfDeprecated( __METHOD__ );
512 return wfGetDB( DB_MASTER );
513 }
514
515 /**
516 * Get options for all SELECT statements
517 *
518 * @param $options Array: an optional options array which'll be appended to
519 * the default
520 * @return Array: options
521 */
522 protected function getSelectOptions( $options = '' ) {
523 if( $this->mForUpdate ) {
524 if( is_array( $options ) ) {
525 $options[] = 'FOR UPDATE';
526 } else {
527 $options = 'FOR UPDATE';
528 }
529 }
530 return $options;
531 }
532
533 /**
534 * @return int Page ID
535 */
536 public function getID() {
537 if( $this->mTitle ) {
538 return $this->mTitle->getArticleID();
539 } else {
540 return 0;
541 }
542 }
543
544 /**
545 * @return bool Whether or not the page exists in the database
546 */
547 public function exists() {
548 return $this->getId() > 0;
549 }
550
551 /**
552 * Check if this page is something we're going to be showing
553 * some sort of sensible content for. If we return false, page
554 * views (plain action=view) will return an HTTP 404 response,
555 * so spiders and robots can know they're following a bad link.
556 *
557 * @return bool
558 */
559 public function hasViewableContent() {
560 return $this->exists() || $this->mTitle->isAlwaysKnown();
561 }
562
563 /**
564 * @return int The view count for the page
565 */
566 public function getCount() {
567 if( -1 == $this->mCounter ) {
568 $id = $this->getID();
569 if( $id == 0 ) {
570 $this->mCounter = 0;
571 } else {
572 $dbr = wfGetDB( DB_SLAVE );
573 $this->mCounter = $dbr->selectField( 'page',
574 'page_counter',
575 array( 'page_id' => $id ),
576 __METHOD__,
577 $this->getSelectOptions()
578 );
579 }
580 }
581 return $this->mCounter;
582 }
583
584 /**
585 * Determine whether a page would be suitable for being counted as an
586 * article in the site_stats table based on the title & its content
587 *
588 * @param $text String: text to analyze
589 * @return bool
590 */
591 public function isCountable( $text ) {
592 global $wgUseCommaCount;
593
594 $token = $wgUseCommaCount ? ',' : '[[';
595 return $this->mTitle->isContentPage() && !$this->isRedirect($text) && in_string($token,$text);
596 }
597
598 /**
599 * Tests if the article text represents a redirect
600 *
601 * @param $text String: FIXME
602 * @return bool
603 */
604 public function isRedirect( $text = false ) {
605 if( $text === false ) {
606 if( $this->mDataLoaded ) {
607 return $this->mIsRedirect;
608 }
609 // Apparently loadPageData was never called
610 $this->loadContent();
611 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
612 } else {
613 $titleObj = Title::newFromRedirect( $text );
614 }
615 return $titleObj !== NULL;
616 }
617
618 /**
619 * Returns true if the currently-referenced revision is the current edit
620 * to this page (and it exists).
621 * @return bool
622 */
623 public function isCurrent() {
624 # If no oldid, this is the current version.
625 if( $this->getOldID() == 0 ) {
626 return true;
627 }
628 return $this->exists() && isset($this->mRevision) && $this->mRevision->isCurrent();
629 }
630
631 /**
632 * Loads everything except the text
633 * This isn't necessary for all uses, so it's only done if needed.
634 */
635 protected function loadLastEdit() {
636 if( -1 != $this->mUser )
637 return;
638
639 # New or non-existent articles have no user information
640 $id = $this->getID();
641 if( 0 == $id ) return;
642
643 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
644 if( !is_null( $this->mLastRevision ) ) {
645 $this->mUser = $this->mLastRevision->getUser();
646 $this->mUserText = $this->mLastRevision->getUserText();
647 $this->mTimestamp = $this->mLastRevision->getTimestamp();
648 $this->mComment = $this->mLastRevision->getComment();
649 $this->mMinorEdit = $this->mLastRevision->isMinor();
650 $this->mRevIdFetched = $this->mLastRevision->getId();
651 }
652 }
653
654 public function getTimestamp() {
655 // Check if the field has been filled by ParserCache::get()
656 if( !$this->mTimestamp ) {
657 $this->loadLastEdit();
658 }
659 return wfTimestamp(TS_MW, $this->mTimestamp);
660 }
661
662 public function getUser() {
663 $this->loadLastEdit();
664 return $this->mUser;
665 }
666
667 public function getUserText() {
668 $this->loadLastEdit();
669 return $this->mUserText;
670 }
671
672 public function getComment() {
673 $this->loadLastEdit();
674 return $this->mComment;
675 }
676
677 public function getMinorEdit() {
678 $this->loadLastEdit();
679 return $this->mMinorEdit;
680 }
681
682 /* Use this to fetch the rev ID used on page views */
683 public function getRevIdFetched() {
684 $this->loadLastEdit();
685 return $this->mRevIdFetched;
686 }
687
688 /**
689 * @param $limit Integer: default 0.
690 * @param $offset Integer: default 0.
691 */
692 public function getContributors($limit = 0, $offset = 0) {
693 # XXX: this is expensive; cache this info somewhere.
694
695 $dbr = wfGetDB( DB_SLAVE );
696 $revTable = $dbr->tableName( 'revision' );
697 $userTable = $dbr->tableName( 'user' );
698
699 $pageId = $this->getId();
700
701 $user = $this->getUser();
702 if ( $user ) {
703 $excludeCond = "AND rev_user != $user";
704 } else {
705 $userText = $dbr->addQuotes( $this->getUserText() );
706 $excludeCond = "AND rev_user_text != $userText";
707 }
708
709 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ); // username hidden?
710
711 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
712 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
713 WHERE rev_page = $pageId
714 $excludeCond
715 AND $deletedBit = 0
716 GROUP BY rev_user, rev_user_text
717 ORDER BY timestamp DESC";
718
719 if ( $limit > 0 )
720 $sql = $dbr->limitResult( $sql, $limit, $offset );
721
722 $sql .= ' ' . $this->getSelectOptions();
723 $res = $dbr->query( $sql, __METHOD__ );
724
725 return new UserArrayFromResult( $res );
726 }
727
728 /**
729 * This is the default action of the index.php entry point: just view the
730 * page of the given title.
731 */
732 public function view() {
733 global $wgUser, $wgOut, $wgRequest, $wgContLang;
734 global $wgEnableParserCache, $wgStylePath, $wgParser;
735 global $wgUseTrackbacks, $wgUseFileCache;
736
737 wfProfileIn( __METHOD__ );
738
739 # Get variables from query string
740 $oldid = $this->getOldID();
741 $parserCache = ParserCache::singleton();
742
743 $parserOptions = clone $this->getParserOptions();
744 # Render printable version, use printable version cache
745 if ( $wgOut->isPrintable() ) {
746 $parserOptions->setIsPrintable( true );
747 }
748
749 # Try client and file cache
750 if( $oldid === 0 && $this->checkTouched() ) {
751 global $wgUseETag;
752 if( $wgUseETag ) {
753 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
754 }
755 # Is is client cached?
756 if( $wgOut->checkLastModified( $this->getTouched() ) ) {
757 wfDebug( __METHOD__.": done 304\n" );
758 wfProfileOut( __METHOD__ );
759 return;
760 # Try file cache
761 } else if( $wgUseFileCache && $this->tryFileCache() ) {
762 wfDebug( __METHOD__.": done file cache\n" );
763 # tell wgOut that output is taken care of
764 $wgOut->disable();
765 $this->viewUpdates();
766 wfProfileOut( __METHOD__ );
767 return;
768 }
769 }
770
771 $sk = $wgUser->getSkin();
772
773 # getOldID may want us to redirect somewhere else
774 if( $this->mRedirectUrl ) {
775 $wgOut->redirect( $this->mRedirectUrl );
776 wfDebug( __METHOD__.": redirecting due to oldid\n" );
777 wfProfileOut( __METHOD__ );
778 return;
779 }
780
781 $wgOut->setArticleFlag( true );
782 # Set page title (may be overridden by DISPLAYTITLE)
783 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
784
785 # If we got diff in the query, we want to see a diff page instead of the article.
786 if( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
787 wfDebug( __METHOD__.": showing diff page\n" );
788 $this->showDiffPage();
789 wfProfileOut( __METHOD__ );
790 return;
791 }
792
793 # Should the parser cache be used?
794 $useParserCache = $this->useParserCache( $oldid );
795 wfDebug( 'Article::view using parser cache: ' . ($useParserCache ? 'yes' : 'no' ) . "\n" );
796 if( $wgUser->getOption( 'stubthreshold' ) ) {
797 wfIncrStats( 'pcache_miss_stub' );
798 }
799
800 # For the main page, overwrite the <title> element with the con-
801 # tents of 'pagetitle-view-mainpage' instead of the default (if
802 # that's not empty).
803 if( $this->mTitle->equals( Title::newMainPage() )
804 && ($m=wfMsgForContent( 'pagetitle-view-mainpage' )) !== '' )
805 {
806 $wgOut->setHTMLTitle( $m );
807 }
808
809 $wasRedirected = $this->showRedirectedFromHeader();
810 $this->showNamespaceHeader();
811
812 # Iterate through the possible ways of constructing the output text.
813 # Keep going until $outputDone is set, or we run out of things to do.
814 $pass = 0;
815 $outputDone = false;
816 while( !$outputDone && ++$pass ){
817 switch( $pass ){
818 case 1:
819 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
820 break;
821
822 case 2:
823 # Try the parser cache
824 if( $useParserCache ) {
825 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
826 if ( $this->mParserOutput !== false ) {
827 wfDebug( __METHOD__.": showing parser cache contents\n" );
828 $wgOut->addParserOutput( $this->mParserOutput );
829 # Ensure that UI elements requiring revision ID have
830 # the correct version information.
831 $wgOut->setRevisionId( $this->mLatest );
832 $outputDone = true;
833 }
834 }
835 break;
836
837 case 3:
838 $text = $this->getContent();
839 if( $text === false || $this->getID() == 0 ) {
840 wfDebug( __METHOD__.": showing missing article\n" );
841 $this->showMissingArticle();
842 wfProfileOut( __METHOD__ );
843 return;
844 }
845
846 # Another whitelist check in case oldid is altering the title
847 if( !$this->mTitle->userCanRead() ) {
848 wfDebug( __METHOD__.": denied on secondary read check\n" );
849 $wgOut->loginToUse();
850 $wgOut->output();
851 $wgOut->disable();
852 wfProfileOut( __METHOD__ );
853 return;
854 }
855
856 # Are we looking at an old revision
857 if( $oldid && !is_null( $this->mRevision ) ) {
858 $this->setOldSubtitle( $oldid );
859 if ( !$this->showDeletedRevisionHeader() ) {
860 wfDebug( __METHOD__.": cannot view deleted revision\n" );
861 wfProfileOut( __METHOD__ );
862 return;
863 }
864 # If this "old" version is the current, then try the parser cache...
865 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
866 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
867 if ( $this->mParserOutput ) {
868 wfDebug( __METHOD__.": showing parser cache for current rev permalink\n" );
869 $wgOut->addParserOutput( $this->mParserOutput );
870 $wgOut->setRevisionId( $this->mLatest );
871 $this->showViewFooter();
872 $this->viewUpdates();
873 wfProfileOut( __METHOD__ );
874 return;
875 }
876 }
877 }
878
879 # Ensure that UI elements requiring revision ID have
880 # the correct version information.
881 $wgOut->setRevisionId( $this->getRevIdFetched() );
882
883 # Pages containing custom CSS or JavaScript get special treatment
884 if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
885 wfDebug( __METHOD__.": showing CSS/JS source\n" );
886 $this->showCssOrJsPage();
887 $outputDone = true;
888 } else if( $rt = Title::newFromRedirectArray( $text ) ) {
889 wfDebug( __METHOD__.": showing redirect=no page\n" );
890 # Viewing a redirect page (e.g. with parameter redirect=no)
891 # Don't append the subtitle if this was an old revision
892 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
893 # Parse just to get categories, displaytitle, etc.
894 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
895 $wgOut->addParserOutputNoText( $this->mParserOutput );
896 $outputDone = true;
897 }
898 break;
899
900 case 4:
901 # Run the parse, protected by a pool counter
902 wfDebug( __METHOD__.": doing uncached parse\n" );
903 $key = $parserCache->getKey( $this, $parserOptions );
904 $poolCounter = PoolCounter::factory( 'Article::view', $key );
905 $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
906 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
907
908 if ( !$status->isOK() ) {
909 # Connection or timeout error
910 $this->showPoolError( $status );
911 wfProfileOut( __METHOD__ );
912 return;
913 } else {
914 $outputDone = true;
915 }
916 break;
917
918 # Should be unreachable, but just in case...
919 default:
920 break 2;
921 }
922 }
923
924 # Now that we've filled $this->mParserOutput, we know whether
925 # there are any __NOINDEX__ tags on the page
926 $policy = $this->getRobotPolicy( 'view' );
927 $wgOut->setIndexPolicy( $policy['index'] );
928 $wgOut->setFollowPolicy( $policy['follow'] );
929
930 $this->showViewFooter();
931 $this->viewUpdates();
932 wfProfileOut( __METHOD__ );
933 }
934
935 /**
936 * Show a diff page according to current request variables. For use within
937 * Article::view() only, other callers should use the DifferenceEngine class.
938 */
939 public function showDiffPage() {
940 global $wgOut, $wgRequest, $wgUser;
941
942 $diff = $wgRequest->getVal( 'diff' );
943 $rcid = $wgRequest->getVal( 'rcid' );
944 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
945 $purge = $wgRequest->getVal( 'action' ) == 'purge';
946 $htmldiff = $wgRequest->getBool( 'htmldiff' );
947 $unhide = $wgRequest->getInt('unhide') == 1;
948 $oldid = $this->getOldID();
949
950 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
951 // DifferenceEngine directly fetched the revision:
952 $this->mRevIdFetched = $de->mNewid;
953 $de->showDiffPage( $diffOnly );
954
955 // Needed to get the page's current revision
956 $this->loadPageData();
957 if( $diff == 0 || $diff == $this->mLatest ) {
958 # Run view updates for current revision only
959 $this->viewUpdates();
960 }
961 }
962
963 /**
964 * Show a page view for a page formatted as CSS or JavaScript. To be called by
965 * Article::view() only.
966 *
967 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
968 * page views.
969 */
970 public function showCssOrJsPage() {
971 global $wgOut;
972 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
973 // Give hooks a chance to customise the output
974 if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
975 // Wrap the whole lot in a <pre> and don't parse
976 $m = array();
977 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
978 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
979 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
980 $wgOut->addHTML( "\n</pre>\n" );
981 }
982 }
983
984 /**
985 * Get the robot policy to be used for the current action=view request.
986 * @return String the policy that should be set
987 * @deprecated use getRobotPolicy() instead, which returns an associative
988 * array
989 */
990 public function getRobotPolicyForView() {
991 wfDeprecated( __FUNC__ );
992 $policy = $this->getRobotPolicy( 'view' );
993 return $policy['index'] . ',' . $policy['follow'];
994 }
995
996 /**
997 * Get the robot policy to be used for the current view
998 * @param $action String the action= GET parameter
999 * @return Array the policy that should be set
1000 * TODO: actions other than 'view'
1001 */
1002 public function getRobotPolicy( $action ){
1003
1004 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1005 global $wgDefaultRobotPolicy, $wgRequest;
1006
1007 $ns = $this->mTitle->getNamespace();
1008 if( $ns == NS_USER || $ns == NS_USER_TALK ) {
1009 # Don't index user and user talk pages for blocked users (bug 11443)
1010 if( !$this->mTitle->isSubpage() ) {
1011 $block = new Block();
1012 if( $block->load( $this->mTitle->getText() ) ) {
1013 return array( 'index' => 'noindex',
1014 'follow' => 'nofollow' );
1015 }
1016 }
1017 }
1018
1019 if( $this->getID() === 0 || $this->getOldID() ) {
1020 # Non-articles (special pages etc), and old revisions
1021 return array( 'index' => 'noindex',
1022 'follow' => 'nofollow' );
1023 } elseif( $wgOut->isPrintable() ) {
1024 # Discourage indexing of printable versions, but encourage following
1025 return array( 'index' => 'noindex',
1026 'follow' => 'follow' );
1027 } elseif( $wgRequest->getInt('curid') ) {
1028 # For ?curid=x urls, disallow indexing
1029 return array( 'index' => 'noindex',
1030 'follow' => 'follow' );
1031 }
1032
1033 # Otherwise, construct the policy based on the various config variables.
1034 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
1035
1036 if( isset( $wgNamespaceRobotPolicies[$ns] ) ){
1037 # Honour customised robot policies for this namespace
1038 $policy = array_merge( $policy,
1039 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] ) );
1040 }
1041 if( $this->mTitle->canUseNoindex() && is_object( $this->mParserOutput ) && $this->mParserOutput->getIndexPolicy() ){
1042 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1043 # a final sanity check that we have really got the parser output.
1044 $policy = array_merge( $policy,
1045 array( 'index' => $this->mParserOutput->getIndexPolicy() ) );
1046 }
1047
1048 if( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ){
1049 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1050 $policy = array_merge( $policy,
1051 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) );
1052 }
1053
1054 return $policy;
1055
1056 }
1057
1058 /**
1059 * Converts a String robot policy into an associative array, to allow
1060 * merging of several policies using array_merge().
1061 * @param $policy Mixed, returns empty array on null/false/'', transparent
1062 * to already-converted arrays, converts String.
1063 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1064 */
1065 public static function formatRobotPolicy( $policy ){
1066 if( is_array( $policy ) ){
1067 return $policy;
1068 } elseif( !$policy ){
1069 return array();
1070 }
1071
1072 $policy = explode( ',', $policy );
1073 $policy = array_map( 'trim', $policy );
1074
1075 $arr = array();
1076 foreach( $policy as $var ){
1077 if( in_array( $var, array('index','noindex') ) ){
1078 $arr['index'] = $var;
1079 } elseif( in_array( $var, array('follow','nofollow') ) ){
1080 $arr['follow'] = $var;
1081 }
1082 }
1083 return $arr;
1084 }
1085
1086 /**
1087 * If this request is a redirect view, send "redirected from" subtitle to
1088 * $wgOut. Returns true if the header was needed, false if this is not a
1089 * redirect view. Handles both local and remote redirects.
1090 */
1091 public function showRedirectedFromHeader() {
1092 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1093
1094 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1095 $sk = $wgUser->getSkin();
1096 if( isset( $this->mRedirectedFrom ) ) {
1097 // This is an internally redirected page view.
1098 // We'll need a backlink to the source page for navigation.
1099 if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1100 $redir = $sk->link(
1101 $this->mRedirectedFrom,
1102 null,
1103 array(),
1104 array( 'redirect' => 'no' ),
1105 array( 'known', 'noclasses' )
1106 );
1107 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1108 $wgOut->setSubtitle( $s );
1109
1110 // Set the fragment if one was specified in the redirect
1111 if( strval( $this->mTitle->getFragment() ) != '' ) {
1112 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1113 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1114 }
1115
1116 // Add a <link rel="canonical"> tag
1117 $wgOut->addLink( array( 'rel' => 'canonical',
1118 'href' => $this->mTitle->getLocalURL() )
1119 );
1120 return true;
1121 }
1122 } elseif( $rdfrom ) {
1123 // This is an externally redirected view, from some other wiki.
1124 // If it was reported from a trusted site, supply a backlink.
1125 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1126 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1127 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1128 $wgOut->setSubtitle( $s );
1129 return true;
1130 }
1131 }
1132 return false;
1133 }
1134
1135 /**
1136 * Show a header specific to the namespace currently being viewed, like
1137 * [[MediaWiki:Talkpagetext]]. For Article::view().
1138 */
1139 public function showNamespaceHeader() {
1140 global $wgOut;
1141 if( $this->mTitle->isTalkPage() ) {
1142 $msg = wfMsgNoTrans( 'talkpageheader' );
1143 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1144 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1145 }
1146 }
1147 }
1148
1149 /**
1150 * Show the footer section of an ordinary page view
1151 */
1152 public function showViewFooter() {
1153 global $wgOut, $wgUseTrackbacks, $wgRequest;
1154 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1155 if( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1156 $wgOut->addWikiMsg('anontalkpagetext');
1157 }
1158
1159 # If we have been passed an &rcid= parameter, we want to give the user a
1160 # chance to mark this new article as patrolled.
1161 $this->showPatrolFooter();
1162
1163 # Trackbacks
1164 if( $wgUseTrackbacks ) {
1165 $this->addTrackbacks();
1166 }
1167 }
1168
1169 /**
1170 * If patrol is possible, output a patrol UI box. This is called from the
1171 * footer section of ordinary page views. If patrol is not possible or not
1172 * desired, does nothing.
1173 */
1174 public function showPatrolFooter() {
1175 global $wgOut, $wgRequest, $wgUser;
1176 $rcid = $wgRequest->getVal( 'rcid' );
1177
1178 if( !$rcid || !$this->mTitle->exists() || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1179 return;
1180 }
1181
1182 $sk = $wgUser->getSkin();
1183
1184 $wgOut->addHTML(
1185 "<div class='patrollink'>" .
1186 wfMsgHtml(
1187 'markaspatrolledlink',
1188 $sk->link(
1189 $this->mTitle,
1190 wfMsgHtml( 'markaspatrolledtext' ),
1191 array(),
1192 array(
1193 'action' => 'markpatrolled',
1194 'rcid' => $rcid
1195 ),
1196 array( 'known', 'noclasses' )
1197 )
1198 ) .
1199 '</div>'
1200 );
1201 }
1202
1203 /**
1204 * Show the error text for a missing article. For articles in the MediaWiki
1205 * namespace, show the default message text. To be called from Article::view().
1206 */
1207 public function showMissingArticle() {
1208 global $wgOut, $wgRequest, $wgUser;
1209
1210 # Show info in user (talk) namespace. Does the user exist?
1211 if ( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
1212 $parts = explode( '/', $this->mTitle->getText() );
1213 $rootPart = $parts[0];
1214 $id = User::idFromName( $rootPart );
1215 $ip = User::isIP( $rootPart );
1216 if ( $id == 0 && !$ip ) { # User does not exist
1217 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
1218 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1219 }
1220 }
1221 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1222 # Show delete and move logs
1223 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle->getPrefixedText(), '',
1224 array( 'lim' => 10,
1225 'conds' => array( "log_action != 'revision'" ),
1226 'showIfEmpty' => false,
1227 'msgKey' => array( 'moveddeleted-notice' ) )
1228 );
1229
1230 # Show error message
1231 $oldid = $this->getOldID();
1232 if( $oldid ) {
1233 $text = wfMsgNoTrans( 'missing-article',
1234 $this->mTitle->getPrefixedText(),
1235 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1236 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1237 // Use the default message text
1238 $text = $this->getContent();
1239 } else {
1240 $createErrors = $this->mTitle->getUserPermissionsErrors( 'create', $wgUser );
1241 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
1242 $errors = array_merge( $createErrors, $editErrors );
1243
1244 if ( !count($errors) )
1245 $text = wfMsgNoTrans( 'noarticletext' );
1246 else
1247 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1248 }
1249 $text = "<div class='noarticletext'>\n$text\n</div>";
1250 if( !$this->hasViewableContent() ) {
1251 // If there's no backing content, send a 404 Not Found
1252 // for better machine handling of broken links.
1253 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1254 }
1255 $wgOut->addWikiText( $text );
1256 }
1257
1258 /**
1259 * If the revision requested for view is deleted, check permissions.
1260 * Send either an error message or a warning header to $wgOut.
1261 * Returns true if the view is allowed, false if not.
1262 */
1263 public function showDeletedRevisionHeader() {
1264 global $wgOut, $wgRequest;
1265 if( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1266 // Not deleted
1267 return true;
1268 }
1269 // If the user is not allowed to see it...
1270 if( !$this->mRevision->userCan(Revision::DELETED_TEXT) ) {
1271 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1272 'rev-deleted-text-permission' );
1273 return false;
1274 // If the user needs to confirm that they want to see it...
1275 } else if( $wgRequest->getInt('unhide') != 1 ) {
1276 # Give explanation and add a link to view the revision...
1277 $oldid = intval( $this->getOldID() );
1278 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1279 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1280 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1281 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1282 array($msg,$link) );
1283 return false;
1284 // We are allowed to see...
1285 } else {
1286 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1287 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1288 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", $msg );
1289 return true;
1290 }
1291 }
1292
1293 /*
1294 * Should the parser cache be used?
1295 */
1296 public function useParserCache( $oldid ) {
1297 global $wgUser, $wgEnableParserCache;
1298
1299 return $wgEnableParserCache
1300 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1301 && $this->exists()
1302 && empty( $oldid )
1303 && !$this->mTitle->isCssOrJsPage()
1304 && !$this->mTitle->isCssJsSubpage();
1305 }
1306
1307 /**
1308 * Execute the uncached parse for action=view
1309 */
1310 public function doViewParse() {
1311 global $wgOut;
1312 $oldid = $this->getOldID();
1313 $useParserCache = $this->useParserCache( $oldid );
1314 $parserOptions = clone $this->getParserOptions();
1315 # Render printable version, use printable version cache
1316 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1317 # Don't show section-edit links on old revisions... this way lies madness.
1318 $parserOptions->setEditSection( $this->isCurrent() );
1319 $useParserCache = $this->useParserCache( $oldid );
1320 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1321 }
1322
1323 /**
1324 * Try to fetch an expired entry from the parser cache. If it is present,
1325 * output it and return true. If it is not present, output nothing and
1326 * return false. This is used as a callback function for
1327 * PoolCounter::executeProtected().
1328 */
1329 public function tryDirtyCache() {
1330 global $wgOut;
1331 $parserCache = ParserCache::singleton();
1332 $options = $this->getParserOptions();
1333 $options->setIsPrintable( $wgOut->isPrintable() );
1334 $output = $parserCache->getDirty( $this, $options );
1335 if ( $output ) {
1336 wfDebug( __METHOD__.": sending dirty output\n" );
1337 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1338 $wgOut->setSquidMaxage( 0 );
1339 $this->mParserOutput = $output;
1340 $wgOut->addParserOutput( $output );
1341 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1342 return true;
1343 } else {
1344 wfDebugLog( 'dirty', "dirty missing\n" );
1345 wfDebug( __METHOD__.": no dirty cache\n" );
1346 return false;
1347 }
1348 }
1349
1350 /**
1351 * Show an error page for an error from the pool counter.
1352 * @param $status Status
1353 */
1354 public function showPoolError( $status ) {
1355 global $wgOut;
1356 $wgOut->clearHTML(); // for release() errors
1357 $wgOut->enableClientCache( false );
1358 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1359 $wgOut->addWikiText(
1360 '<div class="errorbox">' .
1361 $status->getWikiText( false, 'view-pool-error' ) .
1362 '</div>'
1363 );
1364 }
1365
1366 /**
1367 * View redirect
1368 * @param $target Title object or Array of destination(s) to redirect
1369 * @param $appendSubtitle Boolean [optional]
1370 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1371 */
1372 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1373 global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
1374 # Display redirect
1375 if( !is_array( $target ) ) {
1376 $target = array( $target );
1377 }
1378 $imageDir = $wgContLang->getDir();
1379 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1380 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1381 $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
1382
1383 if( $appendSubtitle ) {
1384 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1385 }
1386 $sk = $wgUser->getSkin();
1387 // the loop prepends the arrow image before the link, so the first case needs to be outside
1388 $title = array_shift( $target );
1389 if( $forceKnown ) {
1390 $link = $sk->link(
1391 $title,
1392 htmlspecialchars( $title->getFullText() ),
1393 array(),
1394 array(),
1395 array( 'known', 'noclasses' )
1396 );
1397 } else {
1398 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1399 }
1400 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1401 foreach( $target as $rt ) {
1402 if( $forceKnown ) {
1403 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1404 . $sk->link(
1405 $rt,
1406 htmlspecialchars( $rt->getFullText() ),
1407 array(),
1408 array(),
1409 array( 'known', 'noclasses' )
1410 );
1411 } else {
1412 $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
1413 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1414 }
1415 }
1416 return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
1417 '<span class="redirectText">'.$link.'</span>';
1418
1419 }
1420
1421 public function addTrackbacks() {
1422 global $wgOut, $wgUser;
1423 $dbr = wfGetDB( DB_SLAVE );
1424 $tbs = $dbr->select( 'trackbacks',
1425 array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
1426 array('tb_page' => $this->getID() )
1427 );
1428 if( !$dbr->numRows($tbs) ) return;
1429
1430 $tbtext = "";
1431 while( $o = $dbr->fetchObject($tbs) ) {
1432 $rmvtxt = "";
1433 if( $wgUser->isAllowed( 'trackback' ) ) {
1434 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid=" .
1435 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1436 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1437 }
1438 $tbtext .= "\n";
1439 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
1440 $o->tb_title,
1441 $o->tb_url,
1442 $o->tb_ex,
1443 $o->tb_name,
1444 $rmvtxt);
1445 }
1446 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1447 $this->mTitle->invalidateCache();
1448 }
1449
1450 public function deletetrackback() {
1451 global $wgUser, $wgRequest, $wgOut;
1452 if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
1453 $wgOut->addWikiMsg( 'sessionfailure' );
1454 return;
1455 }
1456
1457 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1458 if( count($permission_errors) ) {
1459 $wgOut->showPermissionsErrorPage( $permission_errors );
1460 return;
1461 }
1462
1463 $db = wfGetDB( DB_MASTER );
1464 $db->delete( 'trackbacks', array('tb_id' => $wgRequest->getInt('tbid')) );
1465
1466 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1467 $this->mTitle->invalidateCache();
1468 }
1469
1470 public function render() {
1471 global $wgOut;
1472 $wgOut->setArticleBodyOnly(true);
1473 $this->view();
1474 }
1475
1476 /**
1477 * Handle action=purge
1478 */
1479 public function purge() {
1480 global $wgUser, $wgRequest, $wgOut;
1481 if( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1482 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1483 $this->doPurge();
1484 $this->view();
1485 }
1486 } else {
1487 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1488 $button = wfMsgExt( 'confirm_purge_button', array('escapenoentities') );
1489 $form = "<form method=\"post\" action=\"$action\">\n" .
1490 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1491 "</form>\n";
1492 $top = wfMsgExt( 'confirm-purge-top', array('parse') );
1493 $bottom = wfMsgExt( 'confirm-purge-bottom', array('parse') );
1494 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1495 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1496 $wgOut->addHTML( $top . $form . $bottom );
1497 }
1498 }
1499
1500 /**
1501 * Perform the actions of a page purging
1502 */
1503 public function doPurge() {
1504 global $wgUseSquid;
1505 // Invalidate the cache
1506 $this->mTitle->invalidateCache();
1507
1508 if( $wgUseSquid ) {
1509 // Commit the transaction before the purge is sent
1510 $dbw = wfGetDB( DB_MASTER );
1511 $dbw->immediateCommit();
1512
1513 // Send purge
1514 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1515 $update->doUpdate();
1516 }
1517 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1518 global $wgMessageCache;
1519 if( $this->getID() == 0 ) {
1520 $text = false;
1521 } else {
1522 $text = $this->getRawText();
1523 }
1524 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1525 }
1526 }
1527
1528 /**
1529 * Insert a new empty page record for this article.
1530 * This *must* be followed up by creating a revision
1531 * and running $this->updateToLatest( $rev_id );
1532 * or else the record will be left in a funky state.
1533 * Best if all done inside a transaction.
1534 *
1535 * @param $dbw Database
1536 * @return int The newly created page_id key, or false if the title already existed
1537 * @private
1538 */
1539 public function insertOn( $dbw ) {
1540 wfProfileIn( __METHOD__ );
1541
1542 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1543 $dbw->insert( 'page', array(
1544 'page_id' => $page_id,
1545 'page_namespace' => $this->mTitle->getNamespace(),
1546 'page_title' => $this->mTitle->getDBkey(),
1547 'page_counter' => 0,
1548 'page_restrictions' => '',
1549 'page_is_redirect' => 0, # Will set this shortly...
1550 'page_is_new' => 1,
1551 'page_random' => wfRandom(),
1552 'page_touched' => $dbw->timestamp(),
1553 'page_latest' => 0, # Fill this in shortly...
1554 'page_len' => 0, # Fill this in shortly...
1555 ), __METHOD__, 'IGNORE' );
1556
1557 $affected = $dbw->affectedRows();
1558 if( $affected ) {
1559 $newid = $dbw->insertId();
1560 $this->mTitle->resetArticleId( $newid );
1561 }
1562 wfProfileOut( __METHOD__ );
1563 return $affected ? $newid : false;
1564 }
1565
1566 /**
1567 * Update the page record to point to a newly saved revision.
1568 *
1569 * @param $dbw Database object
1570 * @param $revision Revision: For ID number, and text used to set
1571 length and redirect status fields
1572 * @param $lastRevision Integer: if given, will not overwrite the page field
1573 * when different from the currently set value.
1574 * Giving 0 indicates the new page flag should be set
1575 * on.
1576 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1577 * removing rows in redirect table.
1578 * @return bool true on success, false on failure
1579 * @private
1580 */
1581 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1582 wfProfileIn( __METHOD__ );
1583
1584 $text = $revision->getText();
1585 $rt = Title::newFromRedirect( $text );
1586
1587 $conditions = array( 'page_id' => $this->getId() );
1588 if( !is_null( $lastRevision ) ) {
1589 # An extra check against threads stepping on each other
1590 $conditions['page_latest'] = $lastRevision;
1591 }
1592
1593 $dbw->update( 'page',
1594 array( /* SET */
1595 'page_latest' => $revision->getId(),
1596 'page_touched' => $dbw->timestamp(),
1597 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1598 'page_is_redirect' => $rt !== NULL ? 1 : 0,
1599 'page_len' => strlen( $text ),
1600 ),
1601 $conditions,
1602 __METHOD__ );
1603
1604 $result = $dbw->affectedRows() != 0;
1605 if( $result ) {
1606 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1607 }
1608
1609 wfProfileOut( __METHOD__ );
1610 return $result;
1611 }
1612
1613 /**
1614 * Add row to the redirect table if this is a redirect, remove otherwise.
1615 *
1616 * @param $dbw Database
1617 * @param $redirectTitle a title object pointing to the redirect target,
1618 * or NULL if this is not a redirect
1619 * @param $lastRevIsRedirect If given, will optimize adding and
1620 * removing rows in redirect table.
1621 * @return bool true on success, false on failure
1622 * @private
1623 */
1624 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1625 // Always update redirects (target link might have changed)
1626 // Update/Insert if we don't know if the last revision was a redirect or not
1627 // Delete if changing from redirect to non-redirect
1628 $isRedirect = !is_null($redirectTitle);
1629 if($isRedirect || is_null($lastRevIsRedirect) || $lastRevIsRedirect !== $isRedirect) {
1630 wfProfileIn( __METHOD__ );
1631 if( $isRedirect ) {
1632 // This title is a redirect, Add/Update row in the redirect table
1633 $set = array( /* SET */
1634 'rd_namespace' => $redirectTitle->getNamespace(),
1635 'rd_title' => $redirectTitle->getDBkey(),
1636 'rd_from' => $this->getId(),
1637 );
1638 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1639 } else {
1640 // This is not a redirect, remove row from redirect table
1641 $where = array( 'rd_from' => $this->getId() );
1642 $dbw->delete( 'redirect', $where, __METHOD__);
1643 }
1644 if( $this->getTitle()->getNamespace() == NS_FILE ) {
1645 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1646 }
1647 wfProfileOut( __METHOD__ );
1648 return ( $dbw->affectedRows() != 0 );
1649 }
1650 return true;
1651 }
1652
1653 /**
1654 * If the given revision is newer than the currently set page_latest,
1655 * update the page record. Otherwise, do nothing.
1656 *
1657 * @param $dbw Database object
1658 * @param $revision Revision object
1659 */
1660 public function updateIfNewerOn( &$dbw, $revision ) {
1661 wfProfileIn( __METHOD__ );
1662 $row = $dbw->selectRow(
1663 array( 'revision', 'page' ),
1664 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1665 array(
1666 'page_id' => $this->getId(),
1667 'page_latest=rev_id' ),
1668 __METHOD__ );
1669 if( $row ) {
1670 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1671 wfProfileOut( __METHOD__ );
1672 return false;
1673 }
1674 $prev = $row->rev_id;
1675 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1676 } else {
1677 # No or missing previous revision; mark the page as new
1678 $prev = 0;
1679 $lastRevIsRedirect = null;
1680 }
1681 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1682 wfProfileOut( __METHOD__ );
1683 return $ret;
1684 }
1685
1686 /**
1687 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1688 * @return string Complete article text, or null if error
1689 */
1690 public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
1691 wfProfileIn( __METHOD__ );
1692 if( strval( $section ) == '' ) {
1693 // Whole-page edit; let the whole text through
1694 } else {
1695 if( is_null($edittime) ) {
1696 $rev = Revision::newFromTitle( $this->mTitle );
1697 } else {
1698 $dbw = wfGetDB( DB_MASTER );
1699 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1700 }
1701 if( !$rev ) {
1702 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1703 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1704 return null;
1705 }
1706 $oldtext = $rev->getText();
1707
1708 if( $section == 'new' ) {
1709 # Inserting a new section
1710 $subject = $summary ? wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n" : '';
1711 $text = strlen( trim( $oldtext ) ) > 0
1712 ? "{$oldtext}\n\n{$subject}{$text}"
1713 : "{$subject}{$text}";
1714 } else {
1715 # Replacing an existing section; roll out the big guns
1716 global $wgParser;
1717 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1718 }
1719 }
1720 wfProfileOut( __METHOD__ );
1721 return $text;
1722 }
1723
1724 /**
1725 * This function is not deprecated until somebody fixes the core not to use
1726 * it. Nevertheless, use Article::doEdit() instead.
1727 */
1728 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false, $bot=false ) {
1729 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1730 ( $isminor ? EDIT_MINOR : 0 ) |
1731 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1732 ( $bot ? EDIT_FORCE_BOT : 0 );
1733
1734 # If this is a comment, add the summary as headline
1735 if( $comment && $summary != "" ) {
1736 $text = wfMsgForContent('newsectionheaderdefaultlevel',$summary) . "\n\n".$text;
1737 }
1738
1739 $this->doEdit( $text, $summary, $flags );
1740
1741 $dbw = wfGetDB( DB_MASTER );
1742 if($watchthis) {
1743 if(!$this->mTitle->userIsWatching()) {
1744 $dbw->begin();
1745 $this->doWatch();
1746 $dbw->commit();
1747 }
1748 } else {
1749 if( $this->mTitle->userIsWatching() ) {
1750 $dbw->begin();
1751 $this->doUnwatch();
1752 $dbw->commit();
1753 }
1754 }
1755 $this->doRedirect( $this->isRedirect( $text ) );
1756 }
1757
1758 /**
1759 * @deprecated use Article::doEdit()
1760 */
1761 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1762 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1763 ( $minor ? EDIT_MINOR : 0 ) |
1764 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1765
1766 $status = $this->doEdit( $text, $summary, $flags );
1767 if( !$status->isOK() ) {
1768 return false;
1769 }
1770
1771 $dbw = wfGetDB( DB_MASTER );
1772 if( $watchthis ) {
1773 if(!$this->mTitle->userIsWatching()) {
1774 $dbw->begin();
1775 $this->doWatch();
1776 $dbw->commit();
1777 }
1778 } else {
1779 if( $this->mTitle->userIsWatching() ) {
1780 $dbw->begin();
1781 $this->doUnwatch();
1782 $dbw->commit();
1783 }
1784 }
1785
1786 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1787 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1788
1789 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1790 return true;
1791 }
1792
1793 /**
1794 * Article::doEdit()
1795 *
1796 * Change an existing article or create a new article. Updates RC and all necessary caches,
1797 * optionally via the deferred update array.
1798 *
1799 * $wgUser must be set before calling this function.
1800 *
1801 * @param $text String: new text
1802 * @param $summary String: edit summary
1803 * @param $flags Integer bitfield:
1804 * EDIT_NEW
1805 * Article is known or assumed to be non-existent, create a new one
1806 * EDIT_UPDATE
1807 * Article is known or assumed to be pre-existing, update it
1808 * EDIT_MINOR
1809 * Mark this edit minor, if the user is allowed to do so
1810 * EDIT_SUPPRESS_RC
1811 * Do not log the change in recentchanges
1812 * EDIT_FORCE_BOT
1813 * Mark the edit a "bot" edit regardless of user rights
1814 * EDIT_DEFER_UPDATES
1815 * Defer some of the updates until the end of index.php
1816 * EDIT_AUTOSUMMARY
1817 * Fill in blank summaries with generated text where possible
1818 *
1819 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1820 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1821 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1822 * edit-already-exists error will be returned. These two conditions are also possible with
1823 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1824 *
1825 * @param $baseRevId the revision ID this edit was based off, if any
1826 * @param $user Optional user object, $wgUser will be used if not passed
1827 *
1828 * @return Status object. Possible errors:
1829 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1830 * edit-gone-missing: In update mode, but the article didn't exist
1831 * edit-conflict: In update mode, the article changed unexpectedly
1832 * edit-no-change: Warning that the text was the same as before
1833 * edit-already-exists: In creation mode, but the article already exists
1834 *
1835 * Extensions may define additional errors.
1836 *
1837 * $return->value will contain an associative array with members as follows:
1838 * new: Boolean indicating if the function attempted to create a new article
1839 * revision: The revision object for the inserted revision, or null
1840 *
1841 * Compatibility note: this function previously returned a boolean value indicating success/failure
1842 */
1843 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1844 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1845
1846 # Low-level sanity check
1847 if( $this->mTitle->getText() == '' ) {
1848 throw new MWException( 'Something is trying to edit an article with an empty title' );
1849 }
1850
1851 wfProfileIn( __METHOD__ );
1852
1853 $user = is_null($user) ? $wgUser : $user;
1854 $status = Status::newGood( array() );
1855
1856 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1857 $this->loadPageData();
1858
1859 if( !($flags & EDIT_NEW) && !($flags & EDIT_UPDATE) ) {
1860 $aid = $this->mTitle->getArticleID();
1861 if( $aid ) {
1862 $flags |= EDIT_UPDATE;
1863 } else {
1864 $flags |= EDIT_NEW;
1865 }
1866 }
1867
1868 if( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1869 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1870 {
1871 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1872 wfProfileOut( __METHOD__ );
1873 if( $status->isOK() ) {
1874 $status->fatal( 'edit-hook-aborted');
1875 }
1876 return $status;
1877 }
1878
1879 # Silently ignore EDIT_MINOR if not allowed
1880 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
1881 $bot = $flags & EDIT_FORCE_BOT;
1882
1883 $oldtext = $this->getRawText(); // current revision
1884 $oldsize = strlen( $oldtext );
1885
1886 # Provide autosummaries if one is not provided and autosummaries are enabled.
1887 if( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1888 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1889 }
1890
1891 $editInfo = $this->prepareTextForEdit( $text );
1892 $text = $editInfo->pst;
1893 $newsize = strlen( $text );
1894
1895 $dbw = wfGetDB( DB_MASTER );
1896 $now = wfTimestampNow();
1897 $this->mTimestamp=$now;
1898
1899 if( $flags & EDIT_UPDATE ) {
1900 # Update article, but only if changed.
1901 $status->value['new'] = false;
1902 # Make sure the revision is either completely inserted or not inserted at all
1903 if( !$wgDBtransactions ) {
1904 $userAbort = ignore_user_abort( true );
1905 }
1906
1907 $revisionId = 0;
1908
1909 $changed = ( strcmp( $text, $oldtext ) != 0 );
1910
1911 if( $changed ) {
1912 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1913 - (int)$this->isCountable( $oldtext );
1914 $this->mTotalAdjustment = 0;
1915
1916 if( !$this->mLatest ) {
1917 # Article gone missing
1918 wfDebug( __METHOD__.": EDIT_UPDATE specified but article doesn't exist\n" );
1919 $status->fatal( 'edit-gone-missing' );
1920 wfProfileOut( __METHOD__ );
1921 return $status;
1922 }
1923
1924 $revision = new Revision( array(
1925 'page' => $this->getId(),
1926 'comment' => $summary,
1927 'minor_edit' => $isminor,
1928 'text' => $text,
1929 'parent_id' => $this->mLatest,
1930 'user' => $user->getId(),
1931 'user_text' => $user->getName(),
1932 ) );
1933
1934 $dbw->begin();
1935 $revisionId = $revision->insertOn( $dbw );
1936
1937 # Update page
1938 #
1939 # Note that we use $this->mLatest instead of fetching a value from the master DB
1940 # during the course of this function. This makes sure that EditPage can detect
1941 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1942 # before this function is called. A previous function used a separate query, this
1943 # creates a window where concurrent edits can cause an ignored edit conflict.
1944 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1945
1946 if( !$ok ) {
1947 /* Belated edit conflict! Run away!! */
1948 $status->fatal( 'edit-conflict' );
1949 # Delete the invalid revision if the DB is not transactional
1950 if( !$wgDBtransactions ) {
1951 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1952 }
1953 $revisionId = 0;
1954 $dbw->rollback();
1955 } else {
1956 global $wgUseRCPatrol;
1957 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
1958 # Update recentchanges
1959 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
1960 # Mark as patrolled if the user can do so
1961 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
1962 # Add RC row to the DB
1963 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1964 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1965 $revisionId, $patrolled
1966 );
1967 # Log auto-patrolled edits
1968 if( $patrolled ) {
1969 PatrolLog::record( $rc, true );
1970 }
1971 }
1972 $user->incEditCount();
1973 $dbw->commit();
1974 }
1975 } else {
1976 $status->warning( 'edit-no-change' );
1977 $revision = null;
1978 // Keep the same revision ID, but do some updates on it
1979 $revisionId = $this->getRevIdFetched();
1980 // Update page_touched, this is usually implicit in the page update
1981 // Other cache updates are done in onArticleEdit()
1982 $this->mTitle->invalidateCache();
1983 }
1984
1985 if( !$wgDBtransactions ) {
1986 ignore_user_abort( $userAbort );
1987 }
1988 // Now that ignore_user_abort is restored, we can respond to fatal errors
1989 if( !$status->isOK() ) {
1990 wfProfileOut( __METHOD__ );
1991 return $status;
1992 }
1993
1994 # Invalidate cache of this article and all pages using this article
1995 # as a template. Partly deferred.
1996 Article::onArticleEdit( $this->mTitle );
1997 # Update links tables, site stats, etc.
1998 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1999 } else {
2000 # Create new article
2001 $status->value['new'] = true;
2002
2003 # Set statistics members
2004 # We work out if it's countable after PST to avoid counter drift
2005 # when articles are created with {{subst:}}
2006 $this->mGoodAdjustment = (int)$this->isCountable( $text );
2007 $this->mTotalAdjustment = 1;
2008
2009 $dbw->begin();
2010
2011 # Add the page record; stake our claim on this title!
2012 # This will return false if the article already exists
2013 $newid = $this->insertOn( $dbw );
2014
2015 if( $newid === false ) {
2016 $dbw->rollback();
2017 $status->fatal( 'edit-already-exists' );
2018 wfProfileOut( __METHOD__ );
2019 return $status;
2020 }
2021
2022 # Save the revision text...
2023 $revision = new Revision( array(
2024 'page' => $newid,
2025 'comment' => $summary,
2026 'minor_edit' => $isminor,
2027 'text' => $text,
2028 'user' => $user->getId(),
2029 'user_text' => $user->getName(),
2030 ) );
2031 $revisionId = $revision->insertOn( $dbw );
2032
2033 $this->mTitle->resetArticleID( $newid );
2034
2035 # Update the page record with revision data
2036 $this->updateRevisionOn( $dbw, $revision, 0 );
2037
2038 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
2039 # Update recentchanges
2040 if( !( $flags & EDIT_SUPPRESS_RC ) ) {
2041 global $wgUseRCPatrol, $wgUseNPPatrol;
2042 # Mark as patrolled if the user can do so
2043 $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
2044 # Add RC row to the DB
2045 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2046 '', strlen($text), $revisionId, $patrolled );
2047 # Log auto-patrolled edits
2048 if( $patrolled ) {
2049 PatrolLog::record( $rc, true );
2050 }
2051 }
2052 $user->incEditCount();
2053 $dbw->commit();
2054
2055 # Update links, etc.
2056 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2057
2058 # Clear caches
2059 Article::onArticleCreate( $this->mTitle );
2060
2061 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2062 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
2063 }
2064
2065 # Do updates right now unless deferral was requested
2066 if( !( $flags & EDIT_DEFER_UPDATES ) ) {
2067 wfDoUpdates();
2068 }
2069
2070 // Return the new revision (or null) to the caller
2071 $status->value['revision'] = $revision;
2072
2073 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2074 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
2075
2076 wfProfileOut( __METHOD__ );
2077 return $status;
2078 }
2079
2080 /**
2081 * @deprecated wrapper for doRedirect
2082 */
2083 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2084 wfDeprecated( __METHOD__ );
2085 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2086 }
2087
2088 /**
2089 * Output a redirect back to the article.
2090 * This is typically used after an edit.
2091 *
2092 * @param $noRedir Boolean: add redirect=no
2093 * @param $sectionAnchor String: section to redirect to, including "#"
2094 * @param $extraQuery String: extra query params
2095 */
2096 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2097 global $wgOut;
2098 if( $noRedir ) {
2099 $query = 'redirect=no';
2100 if( $extraQuery )
2101 $query .= "&$query";
2102 } else {
2103 $query = $extraQuery;
2104 }
2105 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2106 }
2107
2108 /**
2109 * Mark this particular edit/page as patrolled
2110 */
2111 public function markpatrolled() {
2112 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2113 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2114
2115 # If we haven't been given an rc_id value, we can't do anything
2116 $rcid = (int) $wgRequest->getVal('rcid');
2117 $rc = RecentChange::newFromId($rcid);
2118 if( is_null($rc) ) {
2119 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2120 return;
2121 }
2122
2123 #It would be nice to see where the user had actually come from, but for now just guess
2124 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2125 $return = SpecialPage::getTitleFor( $returnto );
2126
2127 $dbw = wfGetDB( DB_MASTER );
2128 $errors = $rc->doMarkPatrolled();
2129
2130 if( in_array(array('rcpatroldisabled'), $errors) ) {
2131 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2132 return;
2133 }
2134
2135 if( in_array(array('hookaborted'), $errors) ) {
2136 // The hook itself has handled any output
2137 return;
2138 }
2139
2140 if( in_array(array('markedaspatrollederror-noautopatrol'), $errors) ) {
2141 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2142 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2143 $wgOut->returnToMain( false, $return );
2144 return;
2145 }
2146
2147 if( !empty($errors) ) {
2148 $wgOut->showPermissionsErrorPage( $errors );
2149 return;
2150 }
2151
2152 # Inform the user
2153 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2154 $wgOut->addWikiMsg( 'markedaspatrolledtext' );
2155 $wgOut->returnToMain( false, $return );
2156 }
2157
2158 /**
2159 * User-interface handler for the "watch" action
2160 */
2161
2162 public function watch() {
2163 global $wgUser, $wgOut;
2164 if( $wgUser->isAnon() ) {
2165 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2166 return;
2167 }
2168 if( wfReadOnly() ) {
2169 $wgOut->readOnlyPage();
2170 return;
2171 }
2172 if( $this->doWatch() ) {
2173 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2174 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2175 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2176 }
2177 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2178 }
2179
2180 /**
2181 * Add this page to $wgUser's watchlist
2182 * @return bool true on successful watch operation
2183 */
2184 public function doWatch() {
2185 global $wgUser;
2186 if( $wgUser->isAnon() ) {
2187 return false;
2188 }
2189 if( wfRunHooks('WatchArticle', array(&$wgUser, &$this)) ) {
2190 $wgUser->addWatch( $this->mTitle );
2191 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
2192 }
2193 return false;
2194 }
2195
2196 /**
2197 * User interface handler for the "unwatch" action.
2198 */
2199 public function unwatch() {
2200 global $wgUser, $wgOut;
2201 if( $wgUser->isAnon() ) {
2202 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2203 return;
2204 }
2205 if( wfReadOnly() ) {
2206 $wgOut->readOnlyPage();
2207 return;
2208 }
2209 if( $this->doUnwatch() ) {
2210 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2211 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2212 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2213 }
2214 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2215 }
2216
2217 /**
2218 * Stop watching a page
2219 * @return bool true on successful unwatch
2220 */
2221 public function doUnwatch() {
2222 global $wgUser;
2223 if( $wgUser->isAnon() ) {
2224 return false;
2225 }
2226 if( wfRunHooks('UnwatchArticle', array(&$wgUser, &$this)) ) {
2227 $wgUser->removeWatch( $this->mTitle );
2228 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
2229 }
2230 return false;
2231 }
2232
2233 /**
2234 * action=protect handler
2235 */
2236 public function protect() {
2237 $form = new ProtectionForm( $this );
2238 $form->execute();
2239 }
2240
2241 /**
2242 * action=unprotect handler (alias)
2243 */
2244 public function unprotect() {
2245 $this->protect();
2246 }
2247
2248 /**
2249 * Update the article's restriction field, and leave a log entry.
2250 *
2251 * @param $limit Array: set of restriction keys
2252 * @param $reason String
2253 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2254 * @param $expiry Array: per restriction type expiration
2255 * @return bool true on success
2256 */
2257 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2258 global $wgUser, $wgRestrictionTypes, $wgContLang;
2259
2260 $id = $this->mTitle->getArticleID();
2261 if ( $id <= 0 ) {
2262 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2263 return false;
2264 }
2265
2266 if ( wfReadOnly() ) {
2267 wfDebug( "updateRestrictions failed: read-only\n" );
2268 return false;
2269 }
2270
2271 if ( !$this->mTitle->userCan( 'protect' ) ) {
2272 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2273 return false;
2274 }
2275
2276 if( !$cascade ) {
2277 $cascade = false;
2278 }
2279
2280 // Take this opportunity to purge out expired restrictions
2281 Title::purgeExpiredRestrictions();
2282
2283 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2284 # we expect a single selection, but the schema allows otherwise.
2285 $current = array();
2286 $updated = Article::flattenRestrictions( $limit );
2287 $changed = false;
2288 foreach( $wgRestrictionTypes as $action ) {
2289 if( isset( $expiry[$action] ) ) {
2290 # Get current restrictions on $action
2291 $aLimits = $this->mTitle->getRestrictions( $action );
2292 $current[$action] = implode( '', $aLimits );
2293 # Are any actual restrictions being dealt with here?
2294 $aRChanged = count($aLimits) || !empty($limit[$action]);
2295 # If something changed, we need to log it. Checking $aRChanged
2296 # assures that "unprotecting" a page that is not protected does
2297 # not log just because the expiry was "changed".
2298 if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2299 $changed = true;
2300 }
2301 }
2302 }
2303
2304 $current = Article::flattenRestrictions( $current );
2305
2306 $changed = ($changed || $current != $updated );
2307 $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
2308 $protect = ( $updated != '' );
2309
2310 # If nothing's changed, do nothing
2311 if( $changed ) {
2312 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2313
2314 $dbw = wfGetDB( DB_MASTER );
2315
2316 # Prepare a null revision to be added to the history
2317 $modified = $current != '' && $protect;
2318 if( $protect ) {
2319 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2320 } else {
2321 $comment_type = 'unprotectedarticle';
2322 }
2323 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2324
2325 # Only restrictions with the 'protect' right can cascade...
2326 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2327 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2328 # The schema allows multiple restrictions
2329 if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
2330 $cascade = false;
2331 $cascade_description = '';
2332 if( $cascade ) {
2333 $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';
2334 }
2335
2336 if( $reason )
2337 $comment .= ": $reason";
2338
2339 $editComment = $comment;
2340 $encodedExpiry = array();
2341 $protect_description = '';
2342 foreach( $limit as $action => $restrictions ) {
2343 if ( !isset($expiry[$action]) )
2344 $expiry[$action] = 'infinite';
2345
2346 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
2347 if( $restrictions != '' ) {
2348 $protect_description .= "[$action=$restrictions] (";
2349 if( $encodedExpiry[$action] != 'infinity' ) {
2350 $protect_description .= wfMsgForContent( 'protect-expiring',
2351 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2352 $wgContLang->date( $expiry[$action], false, false ) ,
2353 $wgContLang->time( $expiry[$action], false, false ) );
2354 } else {
2355 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2356 }
2357 $protect_description .= ') ';
2358 }
2359 }
2360 $protect_description = trim($protect_description);
2361
2362 if( $protect_description && $protect )
2363 $editComment .= " ($protect_description)";
2364 if( $cascade )
2365 $editComment .= "$cascade_description";
2366 # Update restrictions table
2367 foreach( $limit as $action => $restrictions ) {
2368 if($restrictions != '' ) {
2369 $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
2370 array( 'pr_page' => $id,
2371 'pr_type' => $action,
2372 'pr_level' => $restrictions,
2373 'pr_cascade' => ($cascade && $action == 'edit') ? 1 : 0,
2374 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2375 } else {
2376 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2377 'pr_type' => $action ), __METHOD__ );
2378 }
2379 }
2380
2381 # Insert a null revision
2382 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2383 $nullRevId = $nullRevision->insertOn( $dbw );
2384
2385 $latest = $this->getLatest();
2386 # Update page record
2387 $dbw->update( 'page',
2388 array( /* SET */
2389 'page_touched' => $dbw->timestamp(),
2390 'page_restrictions' => '',
2391 'page_latest' => $nullRevId
2392 ), array( /* WHERE */
2393 'page_id' => $id
2394 ), 'Article::protect'
2395 );
2396
2397 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser) );
2398 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2399
2400 # Update the protection log
2401 $log = new LogPage( 'protect' );
2402 if( $protect ) {
2403 $params = array($protect_description,$cascade ? 'cascade' : '');
2404 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason), $params );
2405 } else {
2406 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2407 }
2408
2409 } # End hook
2410 } # End "changed" check
2411
2412 return true;
2413 }
2414
2415 /**
2416 * Take an array of page restrictions and flatten it to a string
2417 * suitable for insertion into the page_restrictions field.
2418 * @param $limit Array
2419 * @return String
2420 */
2421 protected static function flattenRestrictions( $limit ) {
2422 if( !is_array( $limit ) ) {
2423 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2424 }
2425 $bits = array();
2426 ksort( $limit );
2427 foreach( $limit as $action => $restrictions ) {
2428 if( $restrictions != '' ) {
2429 $bits[] = "$action=$restrictions";
2430 }
2431 }
2432 return implode( ':', $bits );
2433 }
2434
2435 /**
2436 * Auto-generates a deletion reason
2437 * @param &$hasHistory Boolean: whether the page has a history
2438 */
2439 public function generateReason( &$hasHistory ) {
2440 global $wgContLang;
2441 $dbw = wfGetDB( DB_MASTER );
2442 // Get the last revision
2443 $rev = Revision::newFromTitle( $this->mTitle );
2444 if( is_null( $rev ) )
2445 return false;
2446
2447 // Get the article's contents
2448 $contents = $rev->getText();
2449 $blank = false;
2450 // If the page is blank, use the text from the previous revision,
2451 // which can only be blank if there's a move/import/protect dummy revision involved
2452 if( $contents == '' ) {
2453 $prev = $rev->getPrevious();
2454 if( $prev ) {
2455 $contents = $prev->getText();
2456 $blank = true;
2457 }
2458 }
2459
2460 // Find out if there was only one contributor
2461 // Only scan the last 20 revisions
2462 $res = $dbw->select( 'revision', 'rev_user_text',
2463 array( 'rev_page' => $this->getID(), $dbw->bitAnd('rev_deleted', Revision::DELETED_USER) . ' = 0' ),
2464 __METHOD__,
2465 array( 'LIMIT' => 20 )
2466 );
2467 if( $res === false )
2468 // This page has no revisions, which is very weird
2469 return false;
2470
2471 $hasHistory = ( $res->numRows() > 1 );
2472 $row = $dbw->fetchObject( $res );
2473 $onlyAuthor = $row->rev_user_text;
2474 // Try to find a second contributor
2475 foreach( $res as $row ) {
2476 if( $row->rev_user_text != $onlyAuthor ) {
2477 $onlyAuthor = false;
2478 break;
2479 }
2480 }
2481 $dbw->freeResult( $res );
2482
2483 // Generate the summary with a '$1' placeholder
2484 if( $blank ) {
2485 // The current revision is blank and the one before is also
2486 // blank. It's just not our lucky day
2487 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2488 } else {
2489 if( $onlyAuthor )
2490 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2491 else
2492 $reason = wfMsgForContent( 'excontent', '$1' );
2493 }
2494
2495 if( $reason == '-' ) {
2496 // Allow these UI messages to be blanked out cleanly
2497 return '';
2498 }
2499
2500 // Replace newlines with spaces to prevent uglyness
2501 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2502 // Calculate the maximum amount of chars to get
2503 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2504 $maxLength = 255 - (strlen( $reason ) - 2) - 3;
2505 $contents = $wgContLang->truncate( $contents, $maxLength );
2506 // Remove possible unfinished links
2507 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2508 // Now replace the '$1' placeholder
2509 $reason = str_replace( '$1', $contents, $reason );
2510 return $reason;
2511 }
2512
2513
2514 /*
2515 * UI entry point for page deletion
2516 */
2517 public function delete() {
2518 global $wgUser, $wgOut, $wgRequest;
2519
2520 $confirm = $wgRequest->wasPosted() &&
2521 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2522
2523 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2524 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2525
2526 $reason = $this->DeleteReasonList;
2527
2528 if( $reason != 'other' && $this->DeleteReason != '' ) {
2529 // Entry from drop down menu + additional comment
2530 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2531 } elseif( $reason == 'other' ) {
2532 $reason = $this->DeleteReason;
2533 }
2534 # Flag to hide all contents of the archived revisions
2535 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2536
2537 # This code desperately needs to be totally rewritten
2538
2539 # Read-only check...
2540 if( wfReadOnly() ) {
2541 $wgOut->readOnlyPage();
2542 return;
2543 }
2544
2545 # Check permissions
2546 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2547
2548 if( count( $permission_errors ) > 0 ) {
2549 $wgOut->showPermissionsErrorPage( $permission_errors );
2550 return;
2551 }
2552
2553 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2554
2555 # Better double-check that it hasn't been deleted yet!
2556 $dbw = wfGetDB( DB_MASTER );
2557 $conds = $this->mTitle->pageCond();
2558 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2559 if( $latest === false ) {
2560 $wgOut->showFatalError(
2561 Html::rawElement(
2562 'div',
2563 array( 'class' => 'error mw-error-cannotdelete' ),
2564 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2565 )
2566 );
2567 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2568 LogEventsList::showLogExtract(
2569 $wgOut,
2570 'delete',
2571 $this->mTitle->getPrefixedText()
2572 );
2573 return;
2574 }
2575
2576 # Hack for big sites
2577 $bigHistory = $this->isBigDeletion();
2578 if( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2579 global $wgLang, $wgDeleteRevisionsLimit;
2580 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2581 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2582 return;
2583 }
2584
2585 if( $confirm ) {
2586 $this->doDelete( $reason, $suppress );
2587 if( $wgRequest->getCheck( 'wpWatch' ) ) {
2588 $this->doWatch();
2589 } elseif( $this->mTitle->userIsWatching() ) {
2590 $this->doUnwatch();
2591 }
2592 return;
2593 }
2594
2595 // Generate deletion reason
2596 $hasHistory = false;
2597 if( !$reason ) $reason = $this->generateReason($hasHistory);
2598
2599 // If the page has a history, insert a warning
2600 if( $hasHistory && !$confirm ) {
2601 $skin = $wgUser->getSkin();
2602 $revisions = $this->estimateRevisionCount();
2603 $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ), $revisions ) . ' ' . $skin->historyLink() . '</strong>' );
2604 if( $bigHistory ) {
2605 global $wgLang, $wgDeleteRevisionsLimit;
2606 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2607 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2608 }
2609 }
2610
2611 return $this->confirmDelete( $reason );
2612 }
2613
2614 /**
2615 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2616 */
2617 public function isBigDeletion() {
2618 global $wgDeleteRevisionsLimit;
2619 if( $wgDeleteRevisionsLimit ) {
2620 $revCount = $this->estimateRevisionCount();
2621 return $revCount > $wgDeleteRevisionsLimit;
2622 }
2623 return false;
2624 }
2625
2626 /**
2627 * @return int approximate revision count
2628 */
2629 public function estimateRevisionCount() {
2630 $dbr = wfGetDB( DB_SLAVE );
2631 // For an exact count...
2632 //return $dbr->selectField( 'revision', 'COUNT(*)',
2633 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2634 return $dbr->estimateRowCount( 'revision', '*',
2635 array( 'rev_page' => $this->getId() ), __METHOD__ );
2636 }
2637
2638 /**
2639 * Get the last N authors
2640 * @param $num Integer: number of revisions to get
2641 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2642 * @return array Array of authors, duplicates not removed
2643 */
2644 public function getLastNAuthors( $num, $revLatest = 0 ) {
2645 wfProfileIn( __METHOD__ );
2646 // First try the slave
2647 // If that doesn't have the latest revision, try the master
2648 $continue = 2;
2649 $db = wfGetDB( DB_SLAVE );
2650 do {
2651 $res = $db->select( array( 'page', 'revision' ),
2652 array( 'rev_id', 'rev_user_text' ),
2653 array(
2654 'page_namespace' => $this->mTitle->getNamespace(),
2655 'page_title' => $this->mTitle->getDBkey(),
2656 'rev_page = page_id'
2657 ), __METHOD__, $this->getSelectOptions( array(
2658 'ORDER BY' => 'rev_timestamp DESC',
2659 'LIMIT' => $num
2660 ) )
2661 );
2662 if( !$res ) {
2663 wfProfileOut( __METHOD__ );
2664 return array();
2665 }
2666 $row = $db->fetchObject( $res );
2667 if( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2668 $db = wfGetDB( DB_MASTER );
2669 $continue--;
2670 } else {
2671 $continue = 0;
2672 }
2673 } while ( $continue );
2674
2675 $authors = array( $row->rev_user_text );
2676 while ( $row = $db->fetchObject( $res ) ) {
2677 $authors[] = $row->rev_user_text;
2678 }
2679 wfProfileOut( __METHOD__ );
2680 return $authors;
2681 }
2682
2683 /**
2684 * Output deletion confirmation dialog
2685 * @param $reason String: prefilled reason
2686 */
2687 public function confirmDelete( $reason ) {
2688 global $wgOut, $wgUser;
2689
2690 wfDebug( "Article::confirmDelete\n" );
2691
2692 $deleteBackLink = $wgUser->getSkin()->link(
2693 $this->mTitle,
2694 null,
2695 array(),
2696 array(),
2697 array( 'known', 'noclasses' )
2698 );
2699 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2700 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2701 $wgOut->addWikiMsg( 'confirmdeletetext' );
2702
2703 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2704
2705 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
2706 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2707 <td></td>
2708 <td class='mw-input'><strong>" .
2709 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2710 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2711 "</strong></td>
2712 </tr>";
2713 } else {
2714 $suppress = '';
2715 }
2716 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2717
2718 $form = Xml::openElement( 'form', array( 'method' => 'post',
2719 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2720 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2721 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2722 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2723 "<tr id=\"wpDeleteReasonListRow\">
2724 <td class='mw-label'>" .
2725 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2726 "</td>
2727 <td class='mw-input'>" .
2728 Xml::listDropDown( 'wpDeleteReasonList',
2729 wfMsgForContent( 'deletereason-dropdown' ),
2730 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2731 "</td>
2732 </tr>
2733 <tr id=\"wpDeleteReasonRow\">
2734 <td class='mw-label'>" .
2735 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2736 "</td>
2737 <td class='mw-input'>" .
2738 Html::input( 'wpReason', $reason, 'text', array(
2739 'size' => '60',
2740 'maxlength' => '255',
2741 'tabindex' => '2',
2742 'id' => 'wpReason',
2743 'autofocus'
2744 ) ) .
2745 "</td>
2746 </tr>
2747 <tr>
2748 <td></td>
2749 <td class='mw-input'>" .
2750 Xml::checkLabel( wfMsg( 'watchthis' ),
2751 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2752 "</td>
2753 </tr>
2754 $suppress
2755 <tr>
2756 <td></td>
2757 <td class='mw-submit'>" .
2758 Xml::submitButton( wfMsg( 'deletepage' ),
2759 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2760 "</td>
2761 </tr>" .
2762 Xml::closeElement( 'table' ) .
2763 Xml::closeElement( 'fieldset' ) .
2764 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2765 Xml::closeElement( 'form' );
2766
2767 if( $wgUser->isAllowed( 'editinterface' ) ) {
2768 $skin = $wgUser->getSkin();
2769 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2770 $link = $skin->link(
2771 $title,
2772 wfMsgHtml( 'delete-edit-reasonlist' ),
2773 array(),
2774 array( 'action' => 'edit' )
2775 );
2776 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2777 }
2778
2779 $wgOut->addHTML( $form );
2780 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2781 LogEventsList::showLogExtract(
2782 $wgOut,
2783 'delete',
2784 $this->mTitle->getPrefixedText()
2785 );
2786 }
2787
2788 /**
2789 * Perform a deletion and output success or failure messages
2790 */
2791 public function doDelete( $reason, $suppress = false ) {
2792 global $wgOut, $wgUser;
2793 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2794
2795 $error = '';
2796 if( wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason, &$error)) ) {
2797 if( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2798 $deleted = $this->mTitle->getPrefixedText();
2799
2800 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2801 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2802
2803 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2804
2805 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2806 $wgOut->returnToMain( false );
2807 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
2808 }
2809 } else {
2810 if( $error == '' ) {
2811 $wgOut->showFatalError(
2812 Html::rawElement(
2813 'div',
2814 array( 'class' => 'error mw-error-cannotdelete' ),
2815 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2816 )
2817 );
2818 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2819 LogEventsList::showLogExtract(
2820 $wgOut,
2821 'delete',
2822 $this->mTitle->getPrefixedText()
2823 );
2824 } else {
2825 $wgOut->showFatalError( $error );
2826 }
2827 }
2828 }
2829
2830 /**
2831 * Back-end article deletion
2832 * Deletes the article with database consistency, writes logs, purges caches
2833 * Returns success
2834 */
2835 public function doDeleteArticle( $reason, $suppress = false, $id = 0 ) {
2836 global $wgUseSquid, $wgDeferredUpdateList;
2837 global $wgUseTrackbacks;
2838
2839 wfDebug( __METHOD__."\n" );
2840
2841 $dbw = wfGetDB( DB_MASTER );
2842 $ns = $this->mTitle->getNamespace();
2843 $t = $this->mTitle->getDBkey();
2844 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2845
2846 if( $t == '' || $id == 0 ) {
2847 return false;
2848 }
2849
2850 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
2851 array_push( $wgDeferredUpdateList, $u );
2852
2853 // Bitfields to further suppress the content
2854 if( $suppress ) {
2855 $bitfield = 0;
2856 // This should be 15...
2857 $bitfield |= Revision::DELETED_TEXT;
2858 $bitfield |= Revision::DELETED_COMMENT;
2859 $bitfield |= Revision::DELETED_USER;
2860 $bitfield |= Revision::DELETED_RESTRICTED;
2861 } else {
2862 $bitfield = 'rev_deleted';
2863 }
2864
2865 $dbw->begin();
2866 // For now, shunt the revision data into the archive table.
2867 // Text is *not* removed from the text table; bulk storage
2868 // is left intact to avoid breaking block-compression or
2869 // immutable storage schemes.
2870 //
2871 // For backwards compatibility, note that some older archive
2872 // table entries will have ar_text and ar_flags fields still.
2873 //
2874 // In the future, we may keep revisions and mark them with
2875 // the rev_deleted field, which is reserved for this purpose.
2876 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2877 array(
2878 'ar_namespace' => 'page_namespace',
2879 'ar_title' => 'page_title',
2880 'ar_comment' => 'rev_comment',
2881 'ar_user' => 'rev_user',
2882 'ar_user_text' => 'rev_user_text',
2883 'ar_timestamp' => 'rev_timestamp',
2884 'ar_minor_edit' => 'rev_minor_edit',
2885 'ar_rev_id' => 'rev_id',
2886 'ar_text_id' => 'rev_text_id',
2887 'ar_text' => '\'\'', // Be explicit to appease
2888 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2889 'ar_len' => 'rev_len',
2890 'ar_page_id' => 'page_id',
2891 'ar_deleted' => $bitfield
2892 ), array(
2893 'page_id' => $id,
2894 'page_id = rev_page'
2895 ), __METHOD__
2896 );
2897
2898 # Delete restrictions for it
2899 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2900
2901 # Now that it's safely backed up, delete it
2902 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
2903 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2904 if( !$ok ) {
2905 $dbw->rollback();
2906 return false;
2907 }
2908
2909 # Fix category table counts
2910 $cats = array();
2911 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2912 foreach( $res as $row ) {
2913 $cats []= $row->cl_to;
2914 }
2915 $this->updateCategoryCounts( array(), $cats );
2916
2917 # If using cascading deletes, we can skip some explicit deletes
2918 if( !$dbw->cascadingDeletes() ) {
2919 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2920
2921 if($wgUseTrackbacks)
2922 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2923
2924 # Delete outgoing links
2925 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2926 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2927 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2928 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2929 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2930 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2931 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2932 }
2933
2934 # If using cleanup triggers, we can skip some manual deletes
2935 if( !$dbw->cleanupTriggers() ) {
2936 # Clean up recentchanges entries...
2937 $dbw->delete( 'recentchanges',
2938 array( 'rc_type != '.RC_LOG,
2939 'rc_namespace' => $this->mTitle->getNamespace(),
2940 'rc_title' => $this->mTitle->getDBkey() ),
2941 __METHOD__ );
2942 $dbw->delete( 'recentchanges',
2943 array( 'rc_type != '.RC_LOG, 'rc_cur_id' => $id ),
2944 __METHOD__ );
2945 }
2946
2947 # Clear caches
2948 Article::onArticleDelete( $this->mTitle );
2949
2950 # Clear the cached article id so the interface doesn't act like we exist
2951 $this->mTitle->resetArticleID( 0 );
2952
2953 # Log the deletion, if the page was suppressed, log it at Oversight instead
2954 $logtype = $suppress ? 'suppress' : 'delete';
2955 $log = new LogPage( $logtype );
2956
2957 # Make sure logging got through
2958 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2959
2960 $dbw->commit();
2961
2962 return true;
2963 }
2964
2965 /**
2966 * Roll back the most recent consecutive set of edits to a page
2967 * from the same user; fails if there are no eligible edits to
2968 * roll back to, e.g. user is the sole contributor. This function
2969 * performs permissions checks on $wgUser, then calls commitRollback()
2970 * to do the dirty work
2971 *
2972 * @param $fromP String: Name of the user whose edits to rollback.
2973 * @param $summary String: Custom summary. Set to default summary if empty.
2974 * @param $token String: Rollback token.
2975 * @param $bot Boolean: If true, mark all reverted edits as bot.
2976 *
2977 * @param $resultDetails Array: contains result-specific array of additional values
2978 * 'alreadyrolled' : 'current' (rev)
2979 * success : 'summary' (str), 'current' (rev), 'target' (rev)
2980 *
2981 * @return array of errors, each error formatted as
2982 * array(messagekey, param1, param2, ...).
2983 * On success, the array is empty. This array can also be passed to
2984 * OutputPage::showPermissionsErrorPage().
2985 */
2986 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
2987 global $wgUser;
2988 $resultDetails = null;
2989
2990 # Check permissions
2991 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
2992 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
2993 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
2994
2995 if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
2996 $errors[] = array( 'sessionfailure' );
2997
2998 if( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
2999 $errors[] = array( 'actionthrottledtext' );
3000 }
3001 # If there were errors, bail out now
3002 if( !empty( $errors ) )
3003 return $errors;
3004
3005 return $this->commitRollback($fromP, $summary, $bot, $resultDetails);
3006 }
3007
3008 /**
3009 * Backend implementation of doRollback(), please refer there for parameter
3010 * and return value documentation
3011 *
3012 * NOTE: This function does NOT check ANY permissions, it just commits the
3013 * rollback to the DB Therefore, you should only call this function direct-
3014 * ly if you want to use custom permissions checks. If you don't, use
3015 * doRollback() instead.
3016 */
3017 public function commitRollback($fromP, $summary, $bot, &$resultDetails) {
3018 global $wgUseRCPatrol, $wgUser, $wgLang;
3019 $dbw = wfGetDB( DB_MASTER );
3020
3021 if( wfReadOnly() ) {
3022 return array( array( 'readonlytext' ) );
3023 }
3024
3025 # Get the last editor
3026 $current = Revision::newFromTitle( $this->mTitle );
3027 if( is_null( $current ) ) {
3028 # Something wrong... no page?
3029 return array(array('notanarticle'));
3030 }
3031
3032 $from = str_replace( '_', ' ', $fromP );
3033 # User name given should match up with the top revision.
3034 # If the user was deleted then $from should be empty.
3035 if( $from != $current->getUserText() ) {
3036 $resultDetails = array( 'current' => $current );
3037 return array(array('alreadyrolled',
3038 htmlspecialchars($this->mTitle->getPrefixedText()),
3039 htmlspecialchars($fromP),
3040 htmlspecialchars($current->getUserText())
3041 ));
3042 }
3043
3044 # Get the last edit not by this guy...
3045 # Note: these may not be public values
3046 $user = intval( $current->getRawUser() );
3047 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3048 $s = $dbw->selectRow( 'revision',
3049 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3050 array( 'rev_page' => $current->getPage(),
3051 "rev_user != {$user} OR rev_user_text != {$user_text}"
3052 ), __METHOD__,
3053 array( 'USE INDEX' => 'page_timestamp',
3054 'ORDER BY' => 'rev_timestamp DESC' )
3055 );
3056 if( $s === false ) {
3057 # No one else ever edited this page
3058 return array(array('cantrollback'));
3059 } else if( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
3060 # Only admins can see this text
3061 return array(array('notvisiblerev'));
3062 }
3063
3064 $set = array();
3065 if( $bot && $wgUser->isAllowed('markbotedits') ) {
3066 # Mark all reverted edits as bot
3067 $set['rc_bot'] = 1;
3068 }
3069 if( $wgUseRCPatrol ) {
3070 # Mark all reverted edits as patrolled
3071 $set['rc_patrolled'] = 1;
3072 }
3073
3074 if( count($set) ) {
3075 $dbw->update( 'recentchanges', $set,
3076 array( /* WHERE */
3077 'rc_cur_id' => $current->getPage(),
3078 'rc_user_text' => $current->getUserText(),
3079 "rc_timestamp > '{$s->rev_timestamp}'",
3080 ), __METHOD__
3081 );
3082 }
3083
3084 # Generate the edit summary if necessary
3085 $target = Revision::newFromId( $s->rev_id );
3086 if( empty( $summary ) ) {
3087 if( $from == '' ) { // no public user name
3088 $summary = wfMsgForContent( 'revertpage-nouser' );
3089 } else {
3090 $summary = wfMsgForContent( 'revertpage' );
3091 }
3092 }
3093
3094 # Allow the custom summary to use the same args as the default message
3095 $args = array(
3096 $target->getUserText(), $from, $s->rev_id,
3097 $wgLang->timeanddate(wfTimestamp(TS_MW, $s->rev_timestamp), true),
3098 $current->getId(), $wgLang->timeanddate($current->getTimestamp())
3099 );
3100 $summary = wfMsgReplaceArgs( $summary, $args );
3101
3102 # Save
3103 $flags = EDIT_UPDATE;
3104
3105 if( $wgUser->isAllowed('minoredit') )
3106 $flags |= EDIT_MINOR;
3107
3108 if( $bot && ($wgUser->isAllowed('markbotedits') || $wgUser->isAllowed('bot')) )
3109 $flags |= EDIT_FORCE_BOT;
3110 # Actually store the edit
3111 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3112 if( !empty( $status->value['revision'] ) ) {
3113 $revId = $status->value['revision']->getId();
3114 } else {
3115 $revId = false;
3116 }
3117
3118 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3119
3120 $resultDetails = array(
3121 'summary' => $summary,
3122 'current' => $current,
3123 'target' => $target,
3124 'newid' => $revId
3125 );
3126 return array();
3127 }
3128
3129 /**
3130 * User interface for rollback operations
3131 */
3132 public function rollback() {
3133 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3134 $details = null;
3135
3136 $result = $this->doRollback(
3137 $wgRequest->getVal( 'from' ),
3138 $wgRequest->getText( 'summary' ),
3139 $wgRequest->getVal( 'token' ),
3140 $wgRequest->getBool( 'bot' ),
3141 $details
3142 );
3143
3144 if( in_array( array( 'actionthrottledtext' ), $result ) ) {
3145 $wgOut->rateLimited();
3146 return;
3147 }
3148 if( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3149 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3150 $errArray = $result[0];
3151 $errMsg = array_shift( $errArray );
3152 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3153 if( isset( $details['current'] ) ){
3154 $current = $details['current'];
3155 if( $current->getComment() != '' ) {
3156 $wgOut->addWikiMsgArray( 'editcomment', array(
3157 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3158 }
3159 }
3160 return;
3161 }
3162 # Display permissions errors before read-only message -- there's no
3163 # point in misleading the user into thinking the inability to rollback
3164 # is only temporary.
3165 if( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3166 # array_diff is completely broken for arrays of arrays, sigh. Re-
3167 # move any 'readonlytext' error manually.
3168 $out = array();
3169 foreach( $result as $error ) {
3170 if( $error != array( 'readonlytext' ) ) {
3171 $out []= $error;
3172 }
3173 }
3174 $wgOut->showPermissionsErrorPage( $out );
3175 return;
3176 }
3177 if( $result == array( array( 'readonlytext' ) ) ) {
3178 $wgOut->readOnlyPage();
3179 return;
3180 }
3181
3182 $current = $details['current'];
3183 $target = $details['target'];
3184 $newId = $details['newid'];
3185 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3186 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3187 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3188 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3189 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3190 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3191 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3192 $wgOut->returnToMain( false, $this->mTitle );
3193
3194 if( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3195 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3196 $de->showDiff( '', '' );
3197 }
3198 }
3199
3200
3201 /**
3202 * Do standard deferred updates after page view
3203 */
3204 public function viewUpdates() {
3205 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3206 if ( wfReadOnly() ) {
3207 return;
3208 }
3209 # Don't update page view counters on views from bot users (bug 14044)
3210 if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
3211 Article::incViewCount( $this->getID() );
3212 $u = new SiteStatsUpdate( 1, 0, 0 );
3213 array_push( $wgDeferredUpdateList, $u );
3214 }
3215 # Update newtalk / watchlist notification status
3216 $wgUser->clearNotification( $this->mTitle );
3217 }
3218
3219 /**
3220 * Prepare text which is about to be saved.
3221 * Returns a stdclass with source, pst and output members
3222 */
3223 public function prepareTextForEdit( $text, $revid=null ) {
3224 if( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid) {
3225 // Already prepared
3226 return $this->mPreparedEdit;
3227 }
3228 global $wgParser;
3229 $edit = (object)array();
3230 $edit->revid = $revid;
3231 $edit->newText = $text;
3232 $edit->pst = $this->preSaveTransform( $text );
3233 $options = $this->getParserOptions();
3234 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3235 $edit->oldText = $this->getContent();
3236 $this->mPreparedEdit = $edit;
3237 return $edit;
3238 }
3239
3240 /**
3241 * Do standard deferred updates after page edit.
3242 * Update links tables, site stats, search index and message cache.
3243 * Purges pages that include this page if the text was changed here.
3244 * Every 100th edit, prune the recent changes table.
3245 *
3246 * @private
3247 * @param $text New text of the article
3248 * @param $summary Edit summary
3249 * @param $minoredit Minor edit
3250 * @param $timestamp_of_pagechange Timestamp associated with the page change
3251 * @param $newid rev_id value of the new revision
3252 * @param $changed Whether or not the content actually changed
3253 */
3254 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3255 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgEnableParserCache;
3256
3257 wfProfileIn( __METHOD__ );
3258
3259 # Parse the text
3260 # Be careful not to double-PST: $text is usually already PST-ed once
3261 if( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3262 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3263 $editInfo = $this->prepareTextForEdit( $text, $newid );
3264 } else {
3265 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3266 $editInfo = $this->mPreparedEdit;
3267 }
3268
3269 # Save it to the parser cache
3270 if( $wgEnableParserCache ) {
3271 $popts = $this->getParserOptions();
3272 $parserCache = ParserCache::singleton();
3273 $parserCache->save( $editInfo->output, $this, $popts );
3274 }
3275
3276 # Update the links tables
3277 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3278 $u->doUpdate();
3279
3280 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3281
3282 if( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3283 if( 0 == mt_rand( 0, 99 ) ) {
3284 // Flush old entries from the `recentchanges` table; we do this on
3285 // random requests so as to avoid an increase in writes for no good reason
3286 global $wgRCMaxAge;
3287 $dbw = wfGetDB( DB_MASTER );
3288 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3289 $recentchanges = $dbw->tableName( 'recentchanges' );
3290 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3291 $dbw->query( $sql );
3292 }
3293 }
3294
3295 $id = $this->getID();
3296 $title = $this->mTitle->getPrefixedDBkey();
3297 $shortTitle = $this->mTitle->getDBkey();
3298
3299 if( 0 == $id ) {
3300 wfProfileOut( __METHOD__ );
3301 return;
3302 }
3303
3304 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3305 array_push( $wgDeferredUpdateList, $u );
3306 $u = new SearchUpdate( $id, $title, $text );
3307 array_push( $wgDeferredUpdateList, $u );
3308
3309 # If this is another user's talk page, update newtalk
3310 # Don't do this if $changed = false otherwise some idiot can null-edit a
3311 # load of user talk pages and piss people off, nor if it's a minor edit
3312 # by a properly-flagged bot.
3313 if( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3314 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3315 if( wfRunHooks('ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3316 $other = User::newFromName( $shortTitle, false );
3317 if( !$other ) {
3318 wfDebug( __METHOD__.": invalid username\n" );
3319 } elseif( User::isIP( $shortTitle ) ) {
3320 // An anonymous user
3321 $other->setNewtalk( true );
3322 } elseif( $other->isLoggedIn() ) {
3323 $other->setNewtalk( true );
3324 } else {
3325 wfDebug( __METHOD__. ": don't need to notify a nonexistent user\n" );
3326 }
3327 }
3328 }
3329
3330 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3331 $wgMessageCache->replace( $shortTitle, $text );
3332 }
3333
3334 wfProfileOut( __METHOD__ );
3335 }
3336
3337 /**
3338 * Perform article updates on a special page creation.
3339 *
3340 * @param $rev Revision object
3341 *
3342 * @todo This is a shitty interface function. Kill it and replace the
3343 * other shitty functions like editUpdates and such so it's not needed
3344 * anymore.
3345 */
3346 public function createUpdates( $rev ) {
3347 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3348 $this->mTotalAdjustment = 1;
3349 $this->editUpdates( $rev->getText(), $rev->getComment(),
3350 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3351 }
3352
3353 /**
3354 * Generate the navigation links when browsing through an article revisions
3355 * It shows the information as:
3356 * Revision as of \<date\>; view current revision
3357 * \<- Previous version | Next Version -\>
3358 *
3359 * @param $oldid String: revision ID of this article revision
3360 */
3361 public function setOldSubtitle( $oldid = 0 ) {
3362 global $wgLang, $wgOut, $wgUser, $wgRequest;
3363
3364 if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3365 return;
3366 }
3367
3368 $revision = Revision::newFromId( $oldid );
3369
3370 $current = ( $oldid == $this->mLatest );
3371 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3372 $tddate = $wgLang->date( $this->mTimestamp, true );
3373 $tdtime = $wgLang->time( $this->mTimestamp, true );
3374 $sk = $wgUser->getSkin();
3375 $lnk = $current
3376 ? wfMsgHtml( 'currentrevisionlink' )
3377 : $sk->link(
3378 $this->mTitle,
3379 wfMsgHtml( 'currentrevisionlink' ),
3380 array(),
3381 array(),
3382 array( 'known', 'noclasses' )
3383 );
3384 $curdiff = $current
3385 ? wfMsgHtml( 'diff' )
3386 : $sk->link(
3387 $this->mTitle,
3388 wfMsgHtml( 'diff' ),
3389 array(),
3390 array(
3391 'diff' => 'cur',
3392 'oldid' => $oldid
3393 ),
3394 array( 'known', 'noclasses' )
3395 );
3396 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3397 $prevlink = $prev
3398 ? $sk->link(
3399 $this->mTitle,
3400 wfMsgHtml( 'previousrevision' ),
3401 array(),
3402 array(
3403 'direction' => 'prev',
3404 'oldid' => $oldid
3405 ),
3406 array( 'known', 'noclasses' )
3407 )
3408 : wfMsgHtml( 'previousrevision' );
3409 $prevdiff = $prev
3410 ? $sk->link(
3411 $this->mTitle,
3412 wfMsgHtml( 'diff' ),
3413 array(),
3414 array(
3415 'diff' => 'prev',
3416 'oldid' => $oldid
3417 ),
3418 array( 'known', 'noclasses' )
3419 )
3420 : wfMsgHtml( 'diff' );
3421 $nextlink = $current
3422 ? wfMsgHtml( 'nextrevision' )
3423 : $sk->link(
3424 $this->mTitle,
3425 wfMsgHtml( 'nextrevision' ),
3426 array(),
3427 array(
3428 'direction' => 'next',
3429 'oldid' => $oldid
3430 ),
3431 array( 'known', 'noclasses' )
3432 );
3433 $nextdiff = $current
3434 ? wfMsgHtml( 'diff' )
3435 : $sk->link(
3436 $this->mTitle,
3437 wfMsgHtml( 'diff' ),
3438 array(),
3439 array(
3440 'diff' => 'next',
3441 'oldid' => $oldid
3442 ),
3443 array( 'known', 'noclasses' )
3444 );
3445
3446 $cdel='';
3447 // Don't show useless link to people who cannot hide revisions
3448 if( $wgUser->isAllowed('deleterevision') || ($revision->getVisibility() && $wgUser->isAllowed('deletedhistory')) ) {
3449 if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3450 // If revision was hidden from sysops
3451 $cdel = wfMsgHtml( 'rev-delundel' );
3452 } else {
3453 $cdel = $sk->link(
3454 SpecialPage::getTitleFor( 'Revisiondelete' ),
3455 wfMsgHtml('rev-delundel'),
3456 array(),
3457 array(
3458 'type' => 'revision',
3459 'target' => urlencode( $this->mTitle->getPrefixedDbkey() ),
3460 'ids' => urlencode( $oldid )
3461 ),
3462 array( 'known', 'noclasses' )
3463 );
3464 // Bolden oversighted content
3465 if( $revision->isDeleted( Revision::DELETED_RESTRICTED ) )
3466 $cdel = "<strong>$cdel</strong>";
3467 }
3468 $cdel = "(<small>$cdel</small>) ";
3469 }
3470 $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
3471 # Show user links if allowed to see them. If hidden, then show them only if requested...
3472 $userlinks = $sk->revUserTools( $revision, !$unhide );
3473
3474 $m = wfMsg( 'revision-info-current' );
3475 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3476 ? 'revision-info-current'
3477 : 'revision-info';
3478
3479 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3480 wfMsgExt(
3481 $infomsg,
3482 array( 'parseinline', 'replaceafter' ),
3483 $td,
3484 $userlinks,
3485 $revision->getID(),
3486 $tddate,
3487 $tdtime,
3488 $revision->getUser()
3489 ) .
3490 "</div>\n" .
3491 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3492 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3493 $wgOut->setSubtitle( $r );
3494 }
3495
3496 /**
3497 * This function is called right before saving the wikitext,
3498 * so we can do things like signatures and links-in-context.
3499 *
3500 * @param $text String
3501 */
3502 public function preSaveTransform( $text ) {
3503 global $wgParser, $wgUser;
3504 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3505 }
3506
3507 /* Caching functions */
3508
3509 /**
3510 * checkLastModified returns true if it has taken care of all
3511 * output to the client that is necessary for this request.
3512 * (that is, it has sent a cached version of the page)
3513 */
3514 protected function tryFileCache() {
3515 static $called = false;
3516 if( $called ) {
3517 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3518 return false;
3519 }
3520 $called = true;
3521 if( $this->isFileCacheable() ) {
3522 $cache = new HTMLFileCache( $this->mTitle );
3523 if( $cache->isFileCacheGood( $this->mTouched ) ) {
3524 wfDebug( "Article::tryFileCache(): about to load file\n" );
3525 $cache->loadFromFileCache();
3526 return true;
3527 } else {
3528 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3529 ob_start( array(&$cache, 'saveToFileCache' ) );
3530 }
3531 } else {
3532 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3533 }
3534 return false;
3535 }
3536
3537 /**
3538 * Check if the page can be cached
3539 * @return bool
3540 */
3541 public function isFileCacheable() {
3542 $cacheable = false;
3543 if( HTMLFileCache::useFileCache() ) {
3544 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3545 // Extension may have reason to disable file caching on some pages.
3546 if( $cacheable ) {
3547 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3548 }
3549 }
3550 return $cacheable;
3551 }
3552
3553 /**
3554 * Loads page_touched and returns a value indicating if it should be used
3555 *
3556 */
3557 public function checkTouched() {
3558 if( !$this->mDataLoaded ) {
3559 $this->loadPageData();
3560 }
3561 return !$this->mIsRedirect;
3562 }
3563
3564 /**
3565 * Get the page_touched field
3566 */
3567 public function getTouched() {
3568 # Ensure that page data has been loaded
3569 if( !$this->mDataLoaded ) {
3570 $this->loadPageData();
3571 }
3572 return $this->mTouched;
3573 }
3574
3575 /**
3576 * Get the page_latest field
3577 */
3578 public function getLatest() {
3579 if( !$this->mDataLoaded ) {
3580 $this->loadPageData();
3581 }
3582 return (int)$this->mLatest;
3583 }
3584
3585 /**
3586 * Edit an article without doing all that other stuff
3587 * The article must already exist; link tables etc
3588 * are not updated, caches are not flushed.
3589 *
3590 * @param $text String: text submitted
3591 * @param $comment String: comment submitted
3592 * @param $minor Boolean: whereas it's a minor modification
3593 */
3594 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3595 wfProfileIn( __METHOD__ );
3596
3597 $dbw = wfGetDB( DB_MASTER );
3598 $revision = new Revision( array(
3599 'page' => $this->getId(),
3600 'text' => $text,
3601 'comment' => $comment,
3602 'minor_edit' => $minor ? 1 : 0,
3603 ) );
3604 $revision->insertOn( $dbw );
3605 $this->updateRevisionOn( $dbw, $revision );
3606
3607 wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $wgUser) );
3608
3609 wfProfileOut( __METHOD__ );
3610 }
3611
3612 /**
3613 * Used to increment the view counter
3614 *
3615 * @param $id Integer: article id
3616 */
3617 public static function incViewCount( $id ) {
3618 $id = intval( $id );
3619 global $wgHitcounterUpdateFreq, $wgDBtype;
3620
3621 $dbw = wfGetDB( DB_MASTER );
3622 $pageTable = $dbw->tableName( 'page' );
3623 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3624 $acchitsTable = $dbw->tableName( 'acchits' );
3625
3626 if( $wgHitcounterUpdateFreq <= 1 ) {
3627 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3628 return;
3629 }
3630
3631 # Not important enough to warrant an error page in case of failure
3632 $oldignore = $dbw->ignoreErrors( true );
3633
3634 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3635
3636 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
3637 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
3638 # Most of the time (or on SQL errors), skip row count check
3639 $dbw->ignoreErrors( $oldignore );
3640 return;
3641 }
3642
3643 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
3644 $row = $dbw->fetchObject( $res );
3645 $rown = intval( $row->n );
3646 if( $rown >= $wgHitcounterUpdateFreq ){
3647 wfProfileIn( 'Article::incViewCount-collect' );
3648 $old_user_abort = ignore_user_abort( true );
3649
3650 if($wgDBtype == 'mysql')
3651 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
3652 $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
3653 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
3654 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
3655 'GROUP BY hc_id');
3656 $dbw->query("DELETE FROM $hitcounterTable");
3657 if($wgDBtype == 'mysql') {
3658 $dbw->query('UNLOCK TABLES');
3659 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
3660 'WHERE page_id = hc_id');
3661 }
3662 else {
3663 $dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
3664 "FROM $acchitsTable WHERE page_id = hc_id");
3665 }
3666 $dbw->query("DROP TABLE $acchitsTable");
3667
3668 ignore_user_abort( $old_user_abort );
3669 wfProfileOut( 'Article::incViewCount-collect' );
3670 }
3671 $dbw->ignoreErrors( $oldignore );
3672 }
3673
3674 /**#@+
3675 * The onArticle*() functions are supposed to be a kind of hooks
3676 * which should be called whenever any of the specified actions
3677 * are done.
3678 *
3679 * This is a good place to put code to clear caches, for instance.
3680 *
3681 * This is called on page move and undelete, as well as edit
3682 *
3683 * @param $title a title object
3684 */
3685
3686 public static function onArticleCreate( $title ) {
3687 # Update existence markers on article/talk tabs...
3688 if( $title->isTalkPage() ) {
3689 $other = $title->getSubjectPage();
3690 } else {
3691 $other = $title->getTalkPage();
3692 }
3693 $other->invalidateCache();
3694 $other->purgeSquid();
3695
3696 $title->touchLinks();
3697 $title->purgeSquid();
3698 $title->deleteTitleProtection();
3699 }
3700
3701 public static function onArticleDelete( $title ) {
3702 global $wgMessageCache;
3703 # Update existence markers on article/talk tabs...
3704 if( $title->isTalkPage() ) {
3705 $other = $title->getSubjectPage();
3706 } else {
3707 $other = $title->getTalkPage();
3708 }
3709 $other->invalidateCache();
3710 $other->purgeSquid();
3711
3712 $title->touchLinks();
3713 $title->purgeSquid();
3714
3715 # File cache
3716 HTMLFileCache::clearFileCache( $title );
3717
3718 # Messages
3719 if( $title->getNamespace() == NS_MEDIAWIKI ) {
3720 $wgMessageCache->replace( $title->getDBkey(), false );
3721 }
3722 # Images
3723 if( $title->getNamespace() == NS_FILE ) {
3724 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3725 $update->doUpdate();
3726 }
3727 # User talk pages
3728 if( $title->getNamespace() == NS_USER_TALK ) {
3729 $user = User::newFromName( $title->getText(), false );
3730 $user->setNewtalk( false );
3731 }
3732 # Image redirects
3733 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3734 }
3735
3736 /**
3737 * Purge caches on page update etc
3738 */
3739 public static function onArticleEdit( $title, $flags = '' ) {
3740 global $wgDeferredUpdateList;
3741
3742 // Invalidate caches of articles which include this page
3743 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3744
3745 // Invalidate the caches of all pages which redirect here
3746 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3747
3748 # Purge squid for this page only
3749 $title->purgeSquid();
3750
3751 # Clear file cache for this page only
3752 HTMLFileCache::clearFileCache( $title );
3753 }
3754
3755 /**#@-*/
3756
3757 /**
3758 * Overriden by ImagePage class, only present here to avoid a fatal error
3759 * Called for ?action=revert
3760 */
3761 public function revert() {
3762 global $wgOut;
3763 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3764 }
3765
3766 /**
3767 * Info about this page
3768 * Called for ?action=info when $wgAllowPageInfo is on.
3769 */
3770 public function info() {
3771 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3772
3773 if( !$wgAllowPageInfo ) {
3774 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3775 return;
3776 }
3777
3778 $page = $this->mTitle->getSubjectPage();
3779
3780 $wgOut->setPagetitle( $page->getPrefixedText() );
3781 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3782 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3783
3784 if( !$this->mTitle->exists() ) {
3785 $wgOut->addHTML( '<div class="noarticletext">' );
3786 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3787 // This doesn't quite make sense; the user is asking for
3788 // information about the _page_, not the message... -- RC
3789 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3790 } else {
3791 $msg = $wgUser->isLoggedIn()
3792 ? 'noarticletext'
3793 : 'noarticletextanon';
3794 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3795 }
3796 $wgOut->addHTML( '</div>' );
3797 } else {
3798 $dbr = wfGetDB( DB_SLAVE );
3799 $wl_clause = array(
3800 'wl_title' => $page->getDBkey(),
3801 'wl_namespace' => $page->getNamespace() );
3802 $numwatchers = $dbr->selectField(
3803 'watchlist',
3804 'COUNT(*)',
3805 $wl_clause,
3806 __METHOD__,
3807 $this->getSelectOptions() );
3808
3809 $pageInfo = $this->pageCountInfo( $page );
3810 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3811
3812 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3813 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
3814 if( $talkInfo ) {
3815 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
3816 }
3817 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3818 if( $talkInfo ) {
3819 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3820 }
3821 $wgOut->addHTML( '</ul>' );
3822 }
3823 }
3824
3825 /**
3826 * Return the total number of edits and number of unique editors
3827 * on a given page. If page does not exist, returns false.
3828 *
3829 * @param $title Title object
3830 * @return array
3831 */
3832 public function pageCountInfo( $title ) {
3833 $id = $title->getArticleId();
3834 if( $id == 0 ) {
3835 return false;
3836 }
3837 $dbr = wfGetDB( DB_SLAVE );
3838 $rev_clause = array( 'rev_page' => $id );
3839 $edits = $dbr->selectField(
3840 'revision',
3841 'COUNT(rev_page)',
3842 $rev_clause,
3843 __METHOD__,
3844 $this->getSelectOptions()
3845 );
3846 $authors = $dbr->selectField(
3847 'revision',
3848 'COUNT(DISTINCT rev_user_text)',
3849 $rev_clause,
3850 __METHOD__,
3851 $this->getSelectOptions()
3852 );
3853 return array( 'edits' => $edits, 'authors' => $authors );
3854 }
3855
3856 /**
3857 * Return a list of templates used by this article.
3858 * Uses the templatelinks table
3859 *
3860 * @return Array of Title objects
3861 */
3862 public function getUsedTemplates() {
3863 $result = array();
3864 $id = $this->mTitle->getArticleID();
3865 if( $id == 0 ) {
3866 return array();
3867 }
3868 $dbr = wfGetDB( DB_SLAVE );
3869 $res = $dbr->select( array( 'templatelinks' ),
3870 array( 'tl_namespace', 'tl_title' ),
3871 array( 'tl_from' => $id ),
3872 __METHOD__ );
3873 if( $res !== false ) {
3874 foreach( $res as $row ) {
3875 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3876 }
3877 }
3878 $dbr->freeResult( $res );
3879 return $result;
3880 }
3881
3882 /**
3883 * Returns a list of hidden categories this page is a member of.
3884 * Uses the page_props and categorylinks tables.
3885 *
3886 * @return Array of Title objects
3887 */
3888 public function getHiddenCategories() {
3889 $result = array();
3890 $id = $this->mTitle->getArticleID();
3891 if( $id == 0 ) {
3892 return array();
3893 }
3894 $dbr = wfGetDB( DB_SLAVE );
3895 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3896 array( 'cl_to' ),
3897 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3898 'page_namespace' => NS_CATEGORY, 'page_title=cl_to'),
3899 __METHOD__ );
3900 if( $res !== false ) {
3901 foreach( $res as $row ) {
3902 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3903 }
3904 }
3905 $dbr->freeResult( $res );
3906 return $result;
3907 }
3908
3909 /**
3910 * Return an applicable autosummary if one exists for the given edit.
3911 * @param $oldtext String: the previous text of the page.
3912 * @param $newtext String: The submitted text of the page.
3913 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3914 * @return string An appropriate autosummary, or an empty string.
3915 */
3916 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3917 # Decide what kind of autosummary is needed.
3918
3919 # Redirect autosummaries
3920 $ot = Title::newFromRedirect( $oldtext );
3921 $rt = Title::newFromRedirect( $newtext );
3922 if( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3923 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3924 }
3925
3926 # New page autosummaries
3927 if( $flags & EDIT_NEW && strlen( $newtext ) ) {
3928 # If they're making a new article, give its text, truncated, in the summary.
3929 global $wgContLang;
3930 $truncatedtext = $wgContLang->truncate(
3931 str_replace("\n", ' ', $newtext),
3932 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3933 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3934 }
3935
3936 # Blanking autosummaries
3937 if( $oldtext != '' && $newtext == '' ) {
3938 return wfMsgForContent( 'autosumm-blank' );
3939 } elseif( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500) {
3940 # Removing more than 90% of the article
3941 global $wgContLang;
3942 $truncatedtext = $wgContLang->truncate(
3943 $newtext,
3944 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3945 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3946 }
3947
3948 # If we reach this point, there's no applicable autosummary for our case, so our
3949 # autosummary is empty.
3950 return '';
3951 }
3952
3953 /**
3954 * Add the primary page-view wikitext to the output buffer
3955 * Saves the text into the parser cache if possible.
3956 * Updates templatelinks if it is out of date.
3957 *
3958 * @param $text String
3959 * @param $cache Boolean
3960 */
3961 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
3962 global $wgOut;
3963
3964 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
3965 $wgOut->addParserOutput( $this->mParserOutput );
3966 }
3967
3968 /**
3969 * This does all the heavy lifting for outputWikitext, except it returns the parser
3970 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
3971 * say, embedding thread pages within a discussion system (LiquidThreads)
3972 */
3973 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
3974 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
3975
3976 if ( !$parserOptions ) {
3977 $parserOptions = $this->getParserOptions();
3978 }
3979
3980 $time = -wfTime();
3981 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
3982 $parserOptions, true, true, $this->getRevIdFetched() );
3983 $time += wfTime();
3984
3985 # Timing hack
3986 if( $time > 3 ) {
3987 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
3988 $this->mTitle->getPrefixedDBkey()));
3989 }
3990
3991 if( $wgEnableParserCache && $cache && $this && $this->mParserOutput->getCacheTime() != -1 ) {
3992 $parserCache = ParserCache::singleton();
3993 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
3994 }
3995 // Make sure file cache is not used on uncacheable content.
3996 // Output that has magic words in it can still use the parser cache
3997 // (if enabled), though it will generally expire sooner.
3998 if( $this->mParserOutput->getCacheTime() == -1 || $this->mParserOutput->containsOldMagic() ) {
3999 $wgUseFileCache = false;
4000 }
4001 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4002 return $this->mParserOutput;
4003 }
4004
4005 /**
4006 * Get parser options suitable for rendering the primary article wikitext
4007 */
4008 public function getParserOptions() {
4009 global $wgUser;
4010 if ( !$this->mParserOptions ) {
4011 $this->mParserOptions = new ParserOptions( $wgUser );
4012 $this->mParserOptions->setTidy( true );
4013 $this->mParserOptions->enableLimitReport();
4014 }
4015 return $this->mParserOptions;
4016 }
4017
4018 protected function doCascadeProtectionUpdates( $parserOutput ) {
4019 if( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4020 return;
4021 }
4022
4023 // templatelinks table may have become out of sync,
4024 // especially if using variable-based transclusions.
4025 // For paranoia, check if things have changed and if
4026 // so apply updates to the database. This will ensure
4027 // that cascaded protections apply as soon as the changes
4028 // are visible.
4029
4030 # Get templates from templatelinks
4031 $id = $this->mTitle->getArticleID();
4032
4033 $tlTemplates = array();
4034
4035 $dbr = wfGetDB( DB_SLAVE );
4036 $res = $dbr->select( array( 'templatelinks' ),
4037 array( 'tl_namespace', 'tl_title' ),
4038 array( 'tl_from' => $id ),
4039 __METHOD__ );
4040
4041 global $wgContLang;
4042 foreach( $res as $row ) {
4043 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4044 }
4045
4046 # Get templates from parser output.
4047 $poTemplates = array();
4048 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4049 foreach ( $templates as $dbk => $id ) {
4050 $poTemplates["$ns:$dbk"] = true;
4051 }
4052 }
4053
4054 # Get the diff
4055 # Note that we simulate array_diff_key in PHP <5.0.x
4056 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4057
4058 if( count( $templates_diff ) > 0 ) {
4059 # Whee, link updates time.
4060 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4061 $u->doUpdate();
4062 }
4063 }
4064
4065 /**
4066 * Update all the appropriate counts in the category table, given that
4067 * we've added the categories $added and deleted the categories $deleted.
4068 *
4069 * @param $added array The names of categories that were added
4070 * @param $deleted array The names of categories that were deleted
4071 * @return null
4072 */
4073 public function updateCategoryCounts( $added, $deleted ) {
4074 $ns = $this->mTitle->getNamespace();
4075 $dbw = wfGetDB( DB_MASTER );
4076
4077 # First make sure the rows exist. If one of the "deleted" ones didn't
4078 # exist, we might legitimately not create it, but it's simpler to just
4079 # create it and then give it a negative value, since the value is bogus
4080 # anyway.
4081 #
4082 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4083 $insertCats = array_merge( $added, $deleted );
4084 if( !$insertCats ) {
4085 # Okay, nothing to do
4086 return;
4087 }
4088 $insertRows = array();
4089 foreach( $insertCats as $cat ) {
4090 $insertRows[] = array( 'cat_id' => $dbw->nextSequenceValue( 'category_id_seq' ),
4091 'cat_title' => $cat );
4092 }
4093 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4094
4095 $addFields = array( 'cat_pages = cat_pages + 1' );
4096 $removeFields = array( 'cat_pages = cat_pages - 1' );
4097 if( $ns == NS_CATEGORY ) {
4098 $addFields[] = 'cat_subcats = cat_subcats + 1';
4099 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4100 } elseif( $ns == NS_FILE ) {
4101 $addFields[] = 'cat_files = cat_files + 1';
4102 $removeFields[] = 'cat_files = cat_files - 1';
4103 }
4104
4105 if( $added ) {
4106 $dbw->update(
4107 'category',
4108 $addFields,
4109 array( 'cat_title' => $added ),
4110 __METHOD__
4111 );
4112 }
4113 if( $deleted ) {
4114 $dbw->update(
4115 'category',
4116 $removeFields,
4117 array( 'cat_title' => $deleted ),
4118 __METHOD__
4119 );
4120 }
4121 }
4122
4123 /** Lightweight method to get the parser output for a page, checking the parser cache
4124 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4125 * consider, so it's not appropriate to use there. */
4126 function getParserOutput( $oldid = null ) {
4127 global $wgEnableParserCache, $wgUser, $wgOut;
4128
4129 // Should the parser cache be used?
4130 $useParserCache = $wgEnableParserCache &&
4131 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4132 $this->exists() &&
4133 $oldid === null;
4134
4135 wfDebug( __METHOD__.': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4136 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4137 wfIncrStats( 'pcache_miss_stub' );
4138 }
4139
4140 $parserOutput = false;
4141 if ( $useParserCache ) {
4142 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4143 }
4144
4145 if ( $parserOutput === false ) {
4146 // Cache miss; parse and output it.
4147 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4148
4149 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4150 } else {
4151 return $parserOutput;
4152 }
4153 }
4154 }